using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Salamax
{
  public static class Startup
  {
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    static extern IntPtr SetFocus(IntPtr hWnd);

    public static BridgeService Service { get; private set; }

    static void Main(string[] args)
    {
      //TODO: Add command-line processing here

      //HACK: For now, assume running in GUI mode
      _Run(true);
    }

    private static void _Run(bool gui)
    {
      try
      {
        const string TITLE = "Salamax Console Window";
        Form frm = null;

        if (gui)
        {
          //Set up this window
          Console.Title = TITLE;

          //Show the main form
          frm = new Main();
          frm.Show();
          frm.Activate();

          Logger.WriteLine("Running in GUI mode.", Logger.Type.Information);
        }

        //Start the bridge service!
        Service = new BridgeService();
        Service.Start();

        bool done = false;
        while (!done)
        {
          //Let any UI catch up
          Application.DoEvents();

          if (gui)
          {
            //Hide the console window if it is somehow visible...
            IntPtr ptr = FindWindow(null, TITLE);
            if (ptr != IntPtr.Zero)
              ShowWindow(ptr, 0);

            //If our main form is gone, then so are we
            if (!Utilities.IsFormOpen(frm))
              done = true;
          }

          Service.ForwardButtonStateChanges();
        }

        Service.Stop();
      }
      catch (Exception ex)
      {
        Logger.WriteLine("Error while running bridge service: " + ex.ToString(), Logger.Type.Error);
      }
    }
  }
}
