using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;

//using System.Timers;
using System.Threading;

namespace VSSMantisService
{
  /// <summary>
  /// Serves as the service object for running the Visual Source Safe
  /// and Mantis integration code every 30 minutes, approximately.
  /// </summary>
  public class VSSMantis : System.ServiceProcess.ServiceBase
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    /// <summary>
    /// Initializes the component and constructs a valid VSSMantis object.
    /// </summary>
    public VSSMantis()
    {
      // This call is required by the Windows.Forms Component Designer.
      InitializeComponent();

      // TODO: Add any initialization after the InitComponent call
    }

    // The main entry point for the process
    static void Main()
    {
      System.ServiceProcess.ServiceBase[] ServicesToRun;

      // More than one user Service may run within the same process. To add
      // another service to this process, change the following line to
      // create a second service object. For example,
      //
      //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
      //
      ServicesToRun = new System.ServiceProcess.ServiceBase[] { new VSSMantis() };

      System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      //
      // VSSMantis
      //
      this.AutoLog = false;
      this.CanShutdown = true;
      this.ServiceName = "VSSM";

    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    /// <summary>
    /// Set things in motion so your service can do its work.
    /// </summary>
    protected override void OnStart(string[] args)
    {
      // TODO: Add code here to start your service.
      string freqs = System.Configuration.ConfigurationSettings.AppSettings["frequency"];
      int freq = int.Parse(freqs, System.Globalization.NumberStyles.Integer);

      timer_ = new System.Timers.Timer(1000*60*freq);
      timer_.AutoReset = true;
      timer_.Elapsed += new System.Timers.ElapsedEventHandler(timer__Elapsed);
      timer_.Start();
    }

    /// <summary>
    /// Stop this service.
    /// </summary>
    protected override void OnStop()
    {
      // TODO: Add code here to perform any tear-down necessary to stop your service.
      if (timer_ == null)
        return;

      timer_.Stop();

      mutex_.WaitOne();
      mutex_.ReleaseMutex();
    }

    /// <summary>
    /// Logic for computer shutting down.
    /// </summary>
    protected override void OnShutdown()
    {
      base.OnShutdown ();

      if (timer_ == null)
        return;

      timer_.Stop();

      mutex_.WaitOne(); // wait until we aren't running anymore
      mutex_.ReleaseMutex();
    }

    System.Timers.Timer timer_;
    Mutex mutex_ = new Mutex();

    private void timer__Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
      timer_.Stop();
      mutex_.WaitOne();

      try
      {
        Integrator integrator = new Integrator();
        integrator.Run();
      }
      catch (Exception ex)
      {
        if (!EventLog.Exists(@"VSSMantis"))
          EventLog.CreateEventSource(@"VSSMantis", @"VSSMantis", @".");

        EventLog el = new EventLog();
        el.Source = @"VSSMantis";

        el.WriteEntry(@"Exception occurred when running integration service: " + ex.Message, EventLogEntryType.Error);

        el.Dispose();
      }

      mutex_.ReleaseMutex();
      timer_.Start();
    }
  }
}