﻿using System;
using System.ServiceProcess;
using Morell.Scriptor.Core;

namespace Morell.Scriptor.Service
{
	/// <summary>
	/// Provides methods to support Scriptor as a Windows service.
	/// </summary>
	/// <seealso cref="System.ServiceProcess.ServiceBase" />
	/// <seealso cref="Morell.Scriptor.Core.IMonitorUpdate" />
	public partial class Service : ServiceBase, IMonitorUpdate
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="Service"/> class.
		/// </summary>
		public Service()
		{
			InitializeComponent();
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
		/// </summary>
		/// <param name="args">Data passed by the start command.</param>
		protected override void OnStart(string[] args)
		{
			try
			{
				Monitor.Initialize(this);
			}
			catch (Exception ex)
			{
				Logger.Info(ex.Message);
			}
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
		/// </summary>
		protected override void OnStop()
		{
			try
			{
				Monitor.Disable();
			}
			catch (Exception ex)
			{
				Logger.Info(ex.Message);
			}
		}

		/// <summary>
		/// Callback triggered when a script is processed.
		/// </summary>
		/// <param name="status">The status information.</param>
		public void Update(StatusUpdate status)
		{
			string message = String.Format("{0} {1} {2} {3} {4}", status.ProjectName, status.DatabaseName, status.FileName, status.Status, status.ErrorMessage);
			if (status.Status == "OK")
				Logger.Info(message);
			else
				Logger.Error(message);
		}
	}
}
