using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using FooEditor.Properties;

namespace FooEditor
{
    static class Program
    {
        static Mutex mutex = new Mutex(false, Resources.ProcessMutex);

        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (mutex.WaitOne(0, false) == false)
            {
                ParseArgs(args);
                return;
            }

            MainForm main = new MainForm();
            main.Shown += new EventHandler((s,e)=>{
                Thread t = new Thread(new ThreadStart(() => {
                    if (args.Length > 0)
                        ParseArgs(args);
                }));
                t.Start();
            });

            Application.Run(main);

            mutex.ReleaseMutex();
        }

        static void ParseArgs(string[] args)
        {
            IPCClient client = new IPCClient();
            if (args.Length == 0)
            {
                client.Send(MainForm.PipeServerName, "ACTIVE");
                return;
            }
            for (int i = 0; i < args.Length; )
            {
                switch (args[i].ToLower())
                {
                    case "-new":
                        client.Send(MainForm.PipeServerName, "NEWDOC");
                        i++;
                        break;
                    case "-linejump":
                        if (i + 1 <= args.Length - 1)
                        {
                            client.Send(MainForm.PipeServerName, string.Format("LINEJUMP\t{0}", args[i + 1]));
                            i += 2;
                        }
                        break;
                    case "-open":
                        if (i + 1 <= args.Length - 1)
                        {
                            client.Send(MainForm.PipeServerName, string.Format("OPEN\t{0}", args[i + 1]));
                            i += 2;
                        }
                        break;
                }
            }
        }

    }
}
