using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Core.Mes.ServerListener
{
    public enum ServerListenerStatus { Stop = 0, Start = 1, SyncFiles = 2 };

    public class Util
    {
        private static System.Diagnostics.EventLog _e = new EventLog();
        private static object lockObj = new object();
        private static string logpath = "";

        public Util()
        {
            if (!EventLog.SourceExists("MesServerListener"))
            {
                EventLog.CreateEventSource("MesServerListener", "MesServerListenerLog");
            }
            _e.Source = "MesServerListener";
        }

        public static bool ExistCoreMesServer(string ServerManagerFileName, bool kill_it)
        {
            System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processList)
            {
                if (process.ProcessName.ToUpper() == "CORE.MES.SERVERMANAGER" &&
                    Path.GetFullPath(process.MainModule.FileName).ToUpper() == Path.GetFullPath(ServerManagerFileName).ToUpper())
                {
                    if (kill_it) process.Kill(); //结束进程
                    return true;
                }
            }
            return false;
        }

        public static bool StartCoreMesServer(string ServerManagerFileName, int retryTimes)
        {
            for (int i = 0; i < retryTimes; i++)
            {
                try
                {
                    string directoryName = Path.GetDirectoryName(ServerManagerFileName);
                    string fileName = Path.GetFileName(ServerManagerFileName);

                    //以当前登录桌面Session启动MES服务；
                    ApplicationLoader.PROCESS_INFORMATION procInfo;
                    ApplicationLoader.StartProcessAndBypassUAC(ServerManagerFileName, out procInfo);

                    //启动不成功时（比如机器刚启动，尚未有人登录时），在Session0级别启动MES服务(此时，看不到服务界面)
                    if (!ExistCoreMesServer(ServerManagerFileName, false))
                    {
                        Process process = new Process();
                        process.StartInfo.WorkingDirectory = directoryName;
                        process.StartInfo.FileName = fileName;
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        process.StartInfo.UseShellExecute = false;
                        process.Start();
                    }

                    //检查服务进程
                    for (int idx = 0; idx < 3; idx++)
                    {
                        Thread.Sleep(500);
                        if (ExistCoreMesServer(ServerManagerFileName, false))
                        {
                            AppListenerLog("MES进程服务开启成功");
                            return true;
                        }
                    }
                    throw new Exception("启动服务后，未检测到相应MES进程!");
                }
                catch (Exception ex)
                {
                    if (i < retryTimes - 1)
                    {
                        AppListenerLog(string.Format("MES进程开启异常:{0} [重试第{1}次]", ex.Message, i + 1));
                    }
                    else
                    {
                        AppListenerLog("开启MES进程失败，错误原因：" + ex.Message);
                    }
                }
            }
            return false;
        }

        public static void CreateLogDirectory()
        {
            try
            {
                try
                {
                    logpath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["ServerListenerLogPath"].Value.ToString();
                }
                catch
                {
                    logpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "\\log\\AppListener");
                }

                logpath = Path.GetFullPath(logpath);

                if (!Directory.Exists(logpath))
                {
                    Directory.CreateDirectory(logpath);
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                _e.WriteEntry("监听程序启动失败，原因是建立监听日志目录发生错误：" + ex.Message, EventLogEntryType.Error);
            }
        }

        public static void AppListenerLog(string str)
        {
            if (!EventLog.SourceExists("MesServerListener"))
            {
                EventLog.CreateEventSource("MesServerListener", "MesServerListenerLog");
            }
            _e.Source = "MesServerListener";
            _e.WriteEntry(str, EventLogEntryType.Error);

            string path = string.Format("{1}AppListenerLog_{0}.txt", DateTime.Now.ToString("yyyy_MM_dd"), logpath);
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            lock (lockObj)
            {
                try
                {
                    using (StreamWriter streamWriter = new StreamWriter(path, true, Encoding.UTF8))
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.AppendLine(string.Format("{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                        stringBuilder.AppendLine(str);
                        stringBuilder.AppendLine("======================================================");
                        streamWriter.WriteLine(stringBuilder.ToString());
                    }
                }
                catch (Exception ex)
                {
                    _e.WriteEntry("监听程序写日志时发生错误：" + ex.Message, EventLogEntryType.Error);
                }
            }
        }
    }
}