using System;
using System.Diagnostics;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Services;
using System.Configuration;
using ChuPiao.Common.Core.Security;

namespace ChuPiao.AutoPrint.Desktop
{
    public class AutoPrintMain
    {
        [STAThread()]
        public static void Main(string[] args)
        {
#if DEBUG
            if (Debugger.IsAttached)
            {
                RunApplication();
                return;
            }
#endif
            int runNum = IsMainAppRun("ChuPiao.AutoPrint.Desktop.exe");
            if (runNum > 1)
            {
                MessageBox.Show("程序已经运行，请不要重复开启");
                return;
            }

            try
            {

                if (AutoUpdate())
                {
                    Application.SetCompatibleTextRenderingDefault(false);
                    RunApplication();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    HandleMainException(ex);
                }
                catch (Exception loadError)
                {
                    // HandleMainException can throw error when log4net is not found
                    MessageBox.Show(loadError.ToString(), "Critical error (Logging service defect?)");
                }
            }
        }
        static void HandleMainException(Exception ex)
        {
            LoggingService.Fatal(ex);
            try
            {
                Application.Run(new ExceptionBox(ex, "Unhandled exception terminated AutoPrint", true));
            }
            catch
            {
                MessageBox.Show(ex.ToString(), "Critical error (cannot use ExceptionBox)");
            }
        }

        static void RunApplication()
        {
            LoggingService.Info("Starting AutoPrint...");
            try
            {
                WorkbenchSingleton.InitializeWorkbench();
            }
            finally
            {
                LoggingService.Info("Leaving RunApplication()");
            }
        }

        private static bool AutoUpdate()
        {
            string updateurl = ConfigurationManager.AppSettings["updateurl"];
            if (!string.IsNullOrEmpty(updateurl))
            {
                try
                {
                    Process pro = new Process();
                    pro.StartInfo.FileName = Application.StartupPath + "\\AutoUpdater.exe";
                    pro.StartInfo.Arguments = updateurl;
                    pro.StartInfo.WorkingDirectory = Application.StartupPath;
                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.CreateNoWindow = true;
                    pro.Start();
                    //主程序一直等待更新程序，要么不需要更新（更新程序会退出），要么被更新程序关掉主程序
                    while (!pro.HasExited)
                    {
                        pro.WaitForExit(1000);
                    }
                    if (pro.ExitCode != 0)
                    {
                        return false;
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("自动升级异常。错误信息：" + exception.Message, "错误提示", MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 判断是否程序正在运行，是的话则关闭程序
        /// </summary>
        /// <param name="mainapp">程序名</param>
        /// <returns>是否程序正在运行</returns>
        static int IsMainAppRun(string mainapp)
        {
            int num = 0;
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
                if (p.ProcessName.ToLower() + ".exe" == mainapp.ToLower())
                {

                    //SetForegroundWindow(p.MainWindowHandle);
                    // isRun = true;
                    num++;
                    //break;
                }
            }
            return num;
        }
    }
}
