using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Media;
using System.Net;
using System.Windows.Forms;

namespace VKontakte
{
	public partial class CaptchaDialog : Form
	{
		public CaptchaDialog()
		{
			this.InitializeComponent();
		}

		protected override void OnShown(EventArgs e)
		{
			base.OnShown(e);
			base.Activate();
			SystemSounds.Exclamation.Play();
		}

		public static string Show(string cap, string captcha_id, WebProxy proxy, string cookies)
		{
			HttpWebRequest httpWebRequest = WebRequest.Create("http://vkontakte.ru//captcha.php?s=1&sid=" + captcha_id.ToString()) as HttpWebRequest;
			if (proxy != null)
			{
				httpWebRequest.Proxy = proxy;
			}
			httpWebRequest.AllowAutoRedirect = false;
			httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6";
			httpWebRequest.ContentType = "application/x-www-form-urlencoded";
			httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
			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.Headers.Add("Cookie", cookies);
			HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
			Stream responseStream = httpWebResponse.GetResponseStream();
			CaptchaDialog captchaDialog = new CaptchaDialog();
			captchaDialog.Text = cap;
			Bitmap bitmap = new Bitmap(responseStream);
			captchaDialog.imgCaptcha.Image = bitmap;
			DialogResult dialogResult = captchaDialog.ShowDialog();
			string text = captchaDialog.txtCode.Text;
			captchaDialog.imgCaptcha.Image = null;
			bitmap.Dispose();
			captchaDialog.Dispose();
			httpWebResponse.Close();
			responseStream.Dispose();
			if (dialogResult != DialogResult.OK)
			{
				return null;
			}
			return text;
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			base.DialogResult = DialogResult.OK;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			base.DialogResult = DialogResult.Cancel;
		}
	}
}
