using AutoUpdaterDotNET;
using DeviceRepair.Models;
using DeviceRepairAndOptimization;
using DeviceRepairAndOptimization.Common;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            bool isAppRunning;

            using (Mutex mutex = new Mutex(true, "设备管理软件", out isAppRunning))
            {
                if (!isAppRunning)
                {
                    // 如果应用程序已在运行，则显示一个消息框并退出。
                    XtraMessageBoxHelper.Error("应用程序已运行。");
                    return;
                }

                Application.ThreadException += Application_ThreadException;
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // 测试其他的窗口
                //Form f = new Form() { Size = new Size(480, 850), StartPosition = FormStartPosition.CenterScreen };
                //f.Controls.Add(new Pages.Tag.xueTagForm() { Dock = DockStyle.Fill });
                //Application.Run(new Pages.Plan.pageMaintenanceRecord());
                //return;


                #region 开个等待窗口,做初始化 主要功能为检测程序配置config中的数据库连接字符串 & 测试连接数据库
                if (args != null && args.Length > 0)
                {
                    //UserInfoModel us1 = JsonConvert.DeserializeObject<UserInfoModel>("{\"AutoID\": 1,\"LoginCode\": \"myl\",\"PassWord\": \"Kanghui2\",\"RealName\": \"管理员\",\"Gender\": 1,\"Birthday\": \"/Date(1693471604770)/\",\"Phone\": \"13800000000\",\"RuleGroup\": 0}");
                    //string aa = JWT.JsonWebToken.Encode(us1, GlobalInfo.SecureKey, JWT.JwtHashAlgorithm.HS256);
                    AutoUpdater.AppTitle = "Device Repair And Optimization";
                    var vUpdateDir = Path.Combine(Application.StartupPath, "Update");
                    if (!Directory.Exists(vUpdateDir))
                    {
                        Directory.CreateDirectory(vUpdateDir);
                    }

                    // 指定下载文件的存储目录
                    AutoUpdater.DownloadPath = vUpdateDir;
                    AutoUpdater.UpdateFormSize = new Size(800, 600);

                    AutoUpdater.Synchronous = true;
                    AutoUpdater.ShowSkipButton = false;
                    AutoUpdater.ShowRemindLaterButton = false;
                    AutoUpdater.Start($"http://{DeviceRepair.Utils.Config.Configurations.Properties.ServiceIP}/{DeviceRepair.Utils.Config.Configurations.Properties.ServiceName}/Update/DOAutoUpdater.xml");

                    try
                    {
                        string argsValue = string.Join("|", args);
                        string usValue = JWT.JsonWebToken.Decode(argsValue, DeviceRepair.Utils.Config.Configurations.Properties.SecureKey, true);
                        UserInfoModel us = JsonConvert.DeserializeObject<UserInfoModel>(usValue);


                        if (us != null)
                        {
                            GlobalInfo.token = argsValue;
                            GlobalInfo.CurrentUser = us;
                            Application.Run(new frm_Launch());
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "错误");
                        return;
                    }
                }

                #endregion


                frmLogin login = new frmLogin();
                if (login.ShowDialog() == DialogResult.OK)
                {
                    Application.Run(new frm_Launch());
                }
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            //1记录日志信息
            Exception ex = e.Exception;
            //2 弹出提示
            XtraMessageBoxHelper.Error(ex.Message);
        }
    }
}