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
	{
		private static Dictionary<int, string> CachMessages = new Dictionary<int, string>();

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

		private int _Code = -1;

		public int Code => _Code;

		public bool FromCach { get; private set; }

		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 result = 0;
			if (match.Success)
			{
				int.TryParse(match.Groups[1].Value, out result);
			}
			string text = null;
			bool flag = false;
			lock (CachMessages)
			{
				flag = CachMessages.ContainsKey(result);
				if (flag)
				{
					text = CachMessages[result];
				}
				else
				{
					VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/blank.php?code=" + result, proxy);
					HttpWebResponse response = vKRequest.GetResponse();
					StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
					while (!streamReader.EndOfStream)
					{
						if (streamReader.ReadLine().Contains("<div class=\"simpleBar clearFix\">"))
						{
							text = streamReader.ReadLine().Trim();
							break;
						}
					}
					streamReader.Close();
					CachMessages.Add(result, text);
				}
			}
			BlankErrorException ex = new BlankErrorException($"{text ?? string.Empty}(бланк#{result})");
			ex._Code = result;
			ex.FromCach = flag;
			return ex;
		}

		public BlankErrorException()
		{
		}

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

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

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

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