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

namespace StarTrinity
{
	public partial class DistributedProxyMainWindow : Form
	{
		readonly DistributedProxySettings _settings;
		Action _readyCallbackDelegate;
		public DistributedProxyMainWindow(DistributedProxySettings settings, Action readyCallbackDelegate)
		{
			this._settings = settings;
			this._readyCallbackDelegate = readyCallbackDelegate;
			InitializeComponent();
			this.textBoxUser.Text = settings.GetSettingValue(DistributedProxySettings.Names.Email, "");
			this.textBoxPassword.Text = settings.GetSettingValue(DistributedProxySettings.Names.Password, "");
			this.FormClosing += new FormClosingEventHandler(DistributedProxyMainWindow_FormClosing);
          
            Load += new EventHandler(DistributedProxyMainWindow_Load);
		}

        void DistributedProxyMainWindow_Load(object sender, EventArgs e)
        {
            if (
                true || // never ask for password at startup
                _settings.GetSettingValue(DistributedProxySettings.Names.PasswordIsSet, "") != ""
                )
			{
				_readyCallbackDelegate();
			    this.ShowInTaskbar = false;
				this.WindowState = FormWindowState.Minimized;
                Hide();
			}
			else
			{
				Show();
				WindowState = FormWindowState.Normal;
				Activate();
			}
            
        }

		bool closing = false;
		void DistributedProxyMainWindow_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (closing) return;
			if (e.CloseReason == CloseReason.UserClosing)
			{
				e.Cancel = true;
				Hide();
			}
		}
		public new void Close()
		{
			closing = true;
			base.Close();
		}

		private void linkLabelRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
            System.Diagnostics.Process.Start("https://proxy.startrinity.com/register.php");
		}

		private void okButton_Click(object sender, EventArgs e)
		{
            _settings.SetSettingValue(DistributedProxySettings.Names.PasswordIsSet, "true");
			_settings.SetSettingValue(DistributedProxySettings.Names.Email, textBoxUser.Text);
			_settings.SetSettingValue(DistributedProxySettings.Names.Password, textBoxPassword.Text);
            
			if (_readyCallbackDelegate != null)
			{
				_readyCallbackDelegate();
				_readyCallbackDelegate = null;
			}
			Hide();
		}
	}
}
