using System;
using System.Threading;
using System.Windows.Forms;

namespace Sleepy
{
	public partial class Window : Form
	{
		private Config config;
		private ServiceManager serviceManager;
		private WaitingForm waitingForm = new WaitingForm();

		public event EventHandler ServiceInstallationComplete;

		public Window(ServiceManager serviceManager, Config config)
		{
			this.serviceManager = serviceManager;
			this.config = config;
			InitializeComponent();

			returnInput.Value = config.Timeout;
			returnInput.ValueChanged += onChange;

			windowsUpdateCheckBox.Checked = config.WindowsUpdate;
			windowsUpdateCheckBox.CheckedChanged += onChange;

			saveButton.Enabled = false;

			if (serviceManager.IsInstalled())
			{
				installButton.Text = "Remove service";
			}

			ServiceInstallationComplete += serviceInstallationCompleted;
		}

		private void saveButton_Click(object sender, EventArgs e)
		{
			config.Timeout = (short)returnInput.Value;
			config.WindowsUpdate = windowsUpdateCheckBox.Checked;
			config.Save();
			saveButton.Enabled = false;

			new Thread(() =>
			{
				Thread.CurrentThread.IsBackground = true;
				serviceManager.Restart();
				BeginInvoke(ServiceInstallationComplete, this, EventArgs.Empty);
			}).Start();

			waitingForm.ShowDialog(this);
		}

		private void onChange(object sender, EventArgs e)
		{
			saveButton.Enabled =
				config.Timeout != (short)returnInput.Value ||
				config.WindowsUpdate != windowsUpdateCheckBox.Checked; ;
		}

		private void serviceInstallationCompleted(object sender, EventArgs e)
		{
			if (serviceManager.IsInstalled())
			{
				installButton.Text = "Remove service";
			}
			else
			{
				installButton.Text = "Install service";
			}

			waitingForm.Hide();
		}

		private void installButton_Click(object sender, EventArgs e)
		{
			new Thread(() =>
			{

				Thread.CurrentThread.IsBackground = true;

				if (serviceManager.IsInstalled())
				{

					try
					{
						serviceManager.Remove();
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message, "Service removal", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}

				}
				else
				{

					try
					{
						serviceManager.Install();
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message, "Service installation", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}

				}

				BeginInvoke(ServiceInstallationComplete, this, EventArgs.Empty);

			}).Start();

			waitingForm.ShowDialog(this);
		}
	}
}