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;
using System.Text.RegularExpressions;

namespace ClipClop.View
{
	public partial class PasswordForm : Form
	{
		public PasswordForm()
		{
			InitializeComponent();

			FormUtil.GeometryFromString(Properties.Settings.Default.WindowGeometryPasswordForm, this);

			this.textBoxPassword.UseSystemPasswordChar = true;
			this.checkBoxShow.Checked = false;
		}

		public string Password
		{
			get
			{
				return this.textBoxPassword.Text;
			}
			set {
				this.textBoxPassword.Text = value;
			}
		}

		public static bool CheckInput(string s)
		{
			if (string.IsNullOrEmpty(s))
				return false;

			Regex r = new Regex(@"[^0-9a-zA-Z]+");
			Match m = r.Match(s);
			if (m.Success)
				return false;
			return true;
		}

		private void PasswordForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (this.DialogResult == DialogResult.OK && !CheckInput(this.textBoxPassword.Text))
			{
				ClipClop.User.Util.ShowWarn(global::ClipClop.Properties.Resources.MSG007);
				e.Cancel = true;
				return;
			}

			Properties.Settings.Default.WindowGeometryPasswordForm = FormUtil.GeometryToString(this);
		}

		private void checkBoxShow_CheckedChanged(object sender, EventArgs e)
		{
			if( this.checkBoxShow.Checked )
				this.textBoxPassword.UseSystemPasswordChar = false;
			else
				this.textBoxPassword.UseSystemPasswordChar = true;
		}

		public static bool ShowInputPassword(ref string s)
		{
			using (PasswordForm f = new PasswordForm())
			{
				f.Password = s;

				DialogResult result = f.ShowDialog();
				if (result != DialogResult.OK)
					return false;
				s = f.Password;
				return true;
			}
		}
	}
}