using Common.system;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

using TStudyDigitalPen.HID;

namespace XHPZ.Desktop
{
    public partial class APP : Application
    {
        #region 全局变量
        /// <summary>
        /// 是否输出测试记录日志
        /// </summary>
        public static bool IsOutputInfoLog = FileToolsCommon.GetConfigValue("IsOutputInfoLog") != "0";
        /// <summary>
        /// 后台线程帮助类
        /// </summary>
        public static BackgroundWorkerHelper BackgroundWorkerHelper => BackgroundWorkerHelper.GetInstance();

        #region 点阵笔
        /// <summary>
        /// 点阵笔
        /// </summary>
        public static DigitalPenHID digitalPen;
        /// <summary>
        /// 笔序号
        /// </summary>
        public static string PenSerial;
        /// <summary>
        /// 笔状态，是否已连接
        /// </summary>
        public static bool PenStatus = false;
        /// <summary>
        /// 手写板状态，是否已连接
        /// </summary>
        public static bool BoardStatus = false;
        #endregion
        #region 腾千里手写笔
        /// <summary>
        /// 腾千里手写笔事件
        /// </summary>
        public static PenEvents TQLPenevents;
        /// <summary>
        /// 腾千里手写笔是否已连接
        /// </summary>
<<<<<<< HEAD
        public static PracticeWindow W_PracticeWindow = null;
=======
        public static bool TQLPenStatus = false;
        #endregion
        #region 页面
        ///// <summary>
        ///// 批注
        ///// </summary>
        //public static PracticeWindow W_PracticeWindow = null;
>>>>>>> a23bdc84b33a613a7ae65513fd285d36f24a5dd6
        #endregion
        #endregion

        [STAThread]
        private static void Main()
        {
            StopSameProcess();
            try
            {
                #region 强制以管理员方式运行 修改人：赵耀 修改时间：2020年9月7日
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                //判断当前登录用户是否为管理员
                //if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                //{
                //    //如果是管理员，则直接运行
                //    W_CreateAMicroLessonWindow = new CreateAMicroLessonWindow();
                //    // 定义Application对象作为整个应用程序入口
                //    Application app = new Application();
                //    app.Run(W_CreateAMicroLessonWindow);
                //    //Application.Run(W_CreateAMicroLessonWindow);
                //}
                //else
                //{
                //    //创建启动对象
                //    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                //    {
                //        UseShellExecute = true,
                //        WorkingDirectory = Environment.CurrentDirectory,
                //        FileName = Assembly.GetExecutingAssembly().Location,
                //        //设置启动动作,确保以管理员身份运行
                //        Verb = "runas"
                //    };
                //    try
                //    {
                //        System.Diagnostics.Process.Start(startInfo);
                //    }
                //    catch
                //    {
                //        return;
                //    }
                //    //退出
                //    //Current.Shutdown();
                //    Environment.Exit(0);

                //}
                #endregion

                try
                {
                    if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "temp"))//清除临时文件
                    {
                        Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + "temp", true);
                    }
                }
                catch (Exception)
                {
                }

                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    //如果是管理员，则直接运行
                    MainWindow mainWindow = new MainWindow();
                    // 定义Application对象作为整个应用程序入口
                    Application app = new Application();
                    app.Run(mainWindow);
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        UseShellExecute = true,
                        WorkingDirectory = Environment.CurrentDirectory,
                        FileName = Assembly.GetExecutingAssembly().Location,
                        //设置启动动作,确保以管理员身份运行
                        Verb = "runas"
                    };
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch
                    {
                        return;
                    }
                    //退出
                    //Current.Shutdown();
                    Environment.Exit(0);

                }
            }
            catch (Exception ex)
            {

                string ErrMessage = "【进程】(Main):进程意外关闭。 " + ex.Message;
                LogHelper.WriteErrLog(ErrMessage, ex);
            }
        }

        #region 杀死已存在的进程
        /// <summary>
        /// 结束已运行的程序
        /// </summary>
        private static void StopSameProcess()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processList = Process.GetProcesses();
            foreach (Process process in processList)
            {
                if (process.ProcessName.ToUpper() == "星火批注")
                {
                    if (process.Id != current.Id) //忽略当前进程
                    {
                        try
                        {
                            process.Kill(); //结束进程
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 杀死正在运行的ffmpeg
        /// </summary>
        public static void Killffmpeg()
        {
            Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
            foreach (Process KillProcess in KillProcessArray)
            {
                KillProcess.Kill();
            }
        }
        #endregion

        /// <summary>
        /// 错误处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyApp_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogHelper.WriteErrLog("未标示错误：" + e.Exception.Message, e.Exception);
            //MessageWindow.Show("程序异常." + Environment.NewLine + e.Exception.Message);
            e.Handled = true;
        }


        #region 内存处理 -创建人：赵耀 -创建时间：2020年8月12日
        /// <summary>
        /// 内存释放压缩
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            //private LierdaCracker cracker = new LierdaCracker();
            //cracker.Cracker(5000);//间隔时间
            //base.OnStartup(e);
            new Thread(o =>
            {
                while (true)
                {
                    try
                    {
                        //FreeMemoryHelper.SetDate();
                        FreeMemoryHelper.ReallocateMemory();
                        Thread.Sleep(20000);//暂定每20秒释放一次
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrLog("【释放内存（MyApp）" + ex.Message, ex);
                    }
                }
            }).Start();
        }

        #endregion 内存处理 -创建人：赵耀 -创建时间：2020年8月12日
    }
}
