using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Resources;
using System.Threading;

namespace Project
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //중복실행방지
            var guidAttr = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true);
            if (guidAttr != null)
            {
                var guida = (GuidAttribute)guidAttr[0];
                var guidstr = guida.Value;
                Mutex mtx = new Mutex(true, guidstr);
                var success = mtx.WaitOne(new TimeSpan(0, 0, 1));
                if (success == false)
                {
                    //MessageBox.Show("중복실행 불가\n\n프로그램이 실행 중 입니다");

                    //"※ Amkor Standard Label Attach"
                    var list = System.Diagnostics.Process.GetProcesses();
                    var prc = list.Where(t => t.ProcessName == "Amkor" && t.MainModule.FileVersionInfo.FileDescription.Contains("Amkor Standard Label")).FirstOrDefault();
                    if (prc != null)
                    {
                        var dlg = MessageBox.Show(
                            "중복 실행이 감지 되었습니다.\r\n" +
                            "현재 실행중인 프로그램을 종료 할까요?\r\n" +
                            "프로그램은 다시 실행하세요", "중복실행", MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

                        if (dlg == DialogResult.Yes)
                        {
                            prc.Kill();
                        }
                    }

                    return;
                }
            }

            //string y, m;
            //var rid = Pub.IsAmkorReelID("RC00004A2130001", out y, out m);

            //var firstsn = "QQZ1";
            //for (int i = 0; i < 1000; i++)
            //{
            //	firstsn = Pub.GetNextSNbySN(firstsn);
            //	Console.WriteLine(string.Format("{0}\t{1}",i, firstsn));
            //}

            //var list = Enum.GetNames(typeof(eDIPin));
            //for(int i = 0; i < list.Length; i++)
            //{
            //	var ediName = (eDIName)i;
            //	Console.WriteLine(string.Format("{0}\t{1}",list[i], ediName));
            //}

            // list = Enum.GetNames(typeof(eDOPin));
            //for (int i = 0; i < list.Length; i++)
            //{
            //	var ediName = (eDOName)i;
            //	Console.WriteLine(string.Format("{0}\t{1}", list[i], ediName));
            //}

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.Run(new fMain());
        }





        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {

            string emsg = "Fatal Error(UHE)\n\n" + e.ExceptionObject.ToString();
            Pub.log.AddE(emsg);
            Pub.log.Flush();
            Util.SaveBugReport(emsg);
            Shutdown();
            var f = new fErrorException(emsg);
            f.ShowDialog();
            Application.ExitThread();
        }

        static void Shutdown()
        {
            Pub.dio.SetOutput(false); //모두끄기
            Pub.sm.setNewStep(StateMachine.eSMStep.IDLE, true);
            Pub.flag.set(eFlag.UserStepCheck, false, "shutdown");
            Pub.log.Add("Program Close");
            Pub.log.Flush();
            Pub.dio.StopMonitor();
            Pub.mot.StopMonitor();
            Pub.sm.Stop();

        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {

            string emsg = "Fatal Error(ATE)\n\n" + e.Exception.ToString();
            //emsg += "stack:" + e.Exception.StackTrace;
            Pub.log.AddE(emsg);
            Pub.log.Flush();
            Util.SaveBugReport(emsg);
            Shutdown();
            var f = new fErrorException(emsg);
            f.ShowDialog();
            Application.ExitThread();
        }
    }
}
