using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;

namespace VKontakte
{
	[Serializable]
	public class BlankErrorException : Exception
	{
		public int Code { get; protected set; }

		public static BlankErrorException GetBlankErrorException(string url)
		{
			int result = 0;
			if (url.Contains("code"))
			{
				int.TryParse(VKClient.Parse(url, "code=", null, 0), out result);
			}
			if (!url.Contains("http://vkontakte.ru/"))
			{
				url = "http://vkontakte.ru/" + url;
			}
			HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
			httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
			httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6";
			httpWebRequest.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.7");
			httpWebRequest.Headers.Add("Accept-Language", "ru,en-us;q=0.7,en;q=0.3");
			httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
			HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
			Stream responseStream = httpWebResponse.GetResponseStream();
			StreamReader streamReader = new StreamReader(responseStream, VKClient.encoding);
			string message = string.Empty;
			do
			{
				if (streamReader.ReadLine().Contains("<div class=\"simpleBar clearFix\">"))
				{
					message = streamReader.ReadLine().Trim();
					break;
				}
			}
			while (!streamReader.EndOfStream);
			streamReader.Close();
			streamReader.Dispose();
			responseStream.Dispose();
			return new BlankErrorException(message, result);
		}

		public BlankErrorException(int code)
		{
			Code = code;
		}

		public BlankErrorException(string message, int code)
			: base(message)
		{
			Code = code;
		}

		public BlankErrorException(string message, int code, Exception inner)
			: base(message, inner)
		{
			Code = code;
		}

		protected BlankErrorException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
}
