using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;

namespace VKontakte
{
	[Serializable]
	public class BlankErrorException : Exception
	{
		public static BlankErrorException Create(string url, IWebProxy proxy)
		{
			if (url[0] == 'r')
			{
				url = url.Substring(1, url.Length - 1);
			}
			Match match = Regex.Match(url, "code=(\\p{Nd}*)&?");
			int num = 0;
			if (match.Success)
			{
				int.TryParse(match.Groups[1].Value, out num);
			}
			string text = null;
			bool flag = false;
			lock (BlankErrorException.CachMessages)
			{
				flag = BlankErrorException.CachMessages.ContainsKey(num);
				if (flag)
				{
					text = BlankErrorException.CachMessages[num];
				}
				else
				{
					VKRequest vkrequest = VKRequest.Create("http://vkontakte.ru/blank.php?code=" + num, proxy);
					HttpWebResponse response = vkrequest.GetResponse();
					StreamReader streamReader = new StreamReader(response.GetResponseStream(), BlankErrorException.enc_ru);
					while (!streamReader.EndOfStream)
					{
						if (streamReader.ReadLine().Contains("<div class=\"simpleBar clearFix\">"))
						{
							text = streamReader.ReadLine().Trim();
							break;
						}
					}
					streamReader.Close();
					BlankErrorException.CachMessages.Add(num, text);
				}
			}
			return new BlankErrorException(string.Format("{0}(бланк#{1})", text ?? string.Empty, num))
			{
				_Code = num,
				FromCach = flag
			};
		}

		public int Code
		{
			get
			{
				return this._Code;
			}
		}

		public bool FromCach { get; private set; }

		public BlankErrorException()
		{
		}

		public BlankErrorException(string message) : base(message)
		{
		}

		public BlankErrorException(string message, int code) : base(message)
		{
			this._Code = code;
		}

		public BlankErrorException(string message, Exception inner) : base(message, inner)
		{
		}

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

		private static Dictionary<int, string> CachMessages = new Dictionary<int, string>();

		private static Encoding enc_ru = Encoding.GetEncoding(1251);

		private int _Code = -1;
	}
}
