using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace pcd_g1
{
	public partial class ActivationDialog : Form
	{
		public ActivationDialog()
		{
			InitializeComponent();
			
			string fname = System.Windows.Forms.Application.StartupPath + @"\key.txt";
			if (System.IO.File.Exists(fname))
			{
				string val = System.IO.File.ReadAllText(fname);
				if (val.Contains('\r')) val = val.Remove(val.IndexOf('\r'));
				this.textBox1.Text = val;
				this.textBox1.Enabled = false;
				this.button1.Enabled = false;
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (run(this.textBox1.Text))
			{
				string fname = System.Windows.Forms.Application.StartupPath + @"\key.txt";
				System.IO.File.WriteAllText(fname, this.textBox1.Text);
				this.DialogResult = System.Windows.Forms.DialogResult.OK;
				this.Close();
			}
			else
			{
				MessageBox.Show("認証に失敗しました");
				this.textBox1.SelectAll();
				this.textBox1.Focus();
			}
		}

		private void Activation_Shown(object sender, EventArgs e)
		{
			if (this.textBox1.Enabled == false)
			{
				if (run(this.textBox1.Text))
				{
					this.DialogResult = System.Windows.Forms.DialogResult.OK;
					this.Close();
				}
				else
				{
					this.textBox1.Enabled = true;
					this.button1.Enabled = true;
					this.textBox1.SelectAll();
				}
			}
			this.textBox1.Focus();
		}

		private bool run(string key)
		{
			if (key == "") return false;

			//パソコン同好会用のキー
			if (encrypt(key) == "8c9b1e8805cd00f904997e86ad521fb0") return true;

			//東京学芸大学附属高校生テスター用キー
			if (encrypt(key) == "5efd981799bd526ad297fd348025fbac") return true;

			return false;
		}

		private string encrypt(string value)
		{
			byte[] data = System.Text.Encoding.UTF8.GetBytes(value);

			System.Security.Cryptography.MD5CryptoServiceProvider md5 =
				new System.Security.Cryptography.MD5CryptoServiceProvider();

			for (int i = 0; i < 10; i++)
			{
				data = md5.ComputeHash(data);
			}

			System.Text.StringBuilder result = new System.Text.StringBuilder();
			foreach (byte b in data)
			{
				result.Append(b.ToString("x2"));
			}

			return result.ToString();
		}

		private void button2_Click(object sender, EventArgs e)
		{
			this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.Close();
		}

		private void button3_Click(object sender, EventArgs e)
		{
			if (Clipboard.ContainsText())
			{
				this.textBox1.Text = Clipboard.GetText();
			}
			this.textBox1.Focus();
			textBox1.SelectAll();
		}

	}
}
