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 static int Timeout
		{
			get
			{
				return CaptchaDialog.timeout;
			}
			set
			{
				CaptchaDialog.timeout = value;
			}
		}

		private void tmrCancel_Tick(object sender, EventArgs e)
		{
			if (this.count-- == 0)
			{
				base.DialogResult = DialogResult.Ignore;
			}
		}

		private CaptchaDialog()
		{
			this.InitializeComponent();
		}

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

		internal static DialogResult Show(string caption, string sid, IWebProxy proxy, ref string key)
		{
			VKRequest vkrequest = VKRequest.Create("http://vkontakte.ru/captcha.php?s=1&sid=" + sid, proxy);
			HttpWebResponse response = vkrequest.GetResponse();
			Stream responseStream = response.GetResponseStream();
			CaptchaDialog captchaDialog = new CaptchaDialog();
			captchaDialog.Text = caption;
			Bitmap bitmap = new Bitmap(responseStream);
			captchaDialog.imgCaptcha.Image = bitmap;
			DialogResult result = captchaDialog.ShowDialog();
			if (captchaDialog.txtKey.Text.Length > 0)
			{
				key = captchaDialog.txtKey.Text;
			}
			captchaDialog.imgCaptcha.Image = null;
			bitmap.Dispose();
			captchaDialog.Dispose();
			responseStream.Close();
			return result;
		}

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

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

		private static volatile int timeout = 30;

		private int count = CaptchaDialog.Timeout;
	}
}
