using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AssistClient
{
    internal static class Program
    { 
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        { 
            Thread.Sleep(500);
            Process instance = RunningInstance();
            if (instance == null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Config.LoadAllConfig();
                while (string.IsNullOrWhiteSpace(Config.DBConStr))
                {
                    Application.Run(new FrmSysSetting());
                    Config.LoadAllConfig();
                }
                Service.InitDB.ConnectionString = Config.DBConStr;
                //Application.Run(new Form1());
                Application.Run(new FrmLogin());
            }
            else
            {
                MessageBox.Show("当前程序已经运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 0);
            }
        }

        //不允许有两个程序同时启动
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历正在有相同名字运行的例程 
            foreach (Process process in processes)
            {
                //忽略现有的例程 
                if (process.Id != current.Id)
                {
                    //确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
                    current.MainModule.FileName)
                    {
                        //返回另一个例程实例 
                        return process;
                    }
                }
            }
            //没有其它的例程，返回Null 
            return null;
        }
    }
}
