using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using Fleck;
using KGIS.Framework.Core.Services;
using KGIS.Framework.Platform;
using KGIS.Framework.Platform.Interface;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using Microsoft.Win32;
using UIShell.OSGi;
namespace Kingo.BuildDB
{
    static class Program
    {
        internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        public static bool v = false;
        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        static void Main(string[] agrs)
        {
            string SystemName = "数 据";
            agrs = new string[] { "NDBG" };
            Platform.Instance.SystemType = SystemTypeEnum.NDBGJK;
            SystemName = "年 度 变 更";
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process curr = Process.GetCurrentProcess();
            List process = Process.GetProcessesByName(curr.ProcessName).ToList();
            if (process != null && process.Count > 0)
            {
                foreach (Process item in process)
                {
                    if (item.Id == curr.Id) continue;
                    ShowWindow(item.MainWindowHandle, 1);
                    SetForegroundWindow(item.MainWindowHandle);
                    Application.Exit();
                    return;
                }
            }
            try
            {
                GdalConfiguration.ConfigureGdal();
                GdalConfiguration.ConfigureOgr();
            }
            catch (Exception ex)
            {
                LogAPI.Debug("Gdal注册失败!");
                LogAPI.Debug(ex);
            }
            try
            {
                ServiceController sc = new ServiceController("ArcGIS License Manager");
                if (!KGIS.Framework.AE.AELicense.AoInit(true) || sc.Status == ServiceControllerStatus.Stopped)
                {
                    MessageHelper.Show("ArcGIS授权服务未启动或已到期,请检查ArcGIS授权!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageHelper.Show("ArcGIS授权服务未启动或已到期,请检查ArcGIS授权!");
                LogAPI.Debug(ex.Message);
                return;
            }
            using (var bundleRuntime = new BundleRuntime())
            {
                #region
                int loadedBundleCount = 0;
                Action action = null;
                IAsyncResult asyncResult = null;
                IPluginStart startPlugin = null;
                List bundles = new List();
                //插件状态发生改变事件,用来加载启动插件的进度
                EventHandler bundleStateChangeEventHandler = (sender, e) =>
                {
                    if (e.CurrentState != BundleState.Starting || e.Bundle.Name == "SystemBundle")
                        return;
                    if (startPlugin == null)
                        startPlugin = bundleRuntime.GetFirstOrDefaultService();
                    string[] Name_ID = e.Bundle.Name.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (startPlugin != null)
                    {
                        startPlugin.SetTitle(string.Format(ConfigurationManager.AppSettings.Get("APPName"), SystemName));
                        startPlugin.SetSystemType(SystemTypeEnum.NDBGJK.ToString());
                        if (!startPlugin.IsShow)
                        {
                            action = (ar) =>
                            {
                                if (ar)
                                {
                                    startPlugin.ShowDialog();
                                }
                            };
                            asyncResult = action.BeginInvoke(true, null, null);
                            //等待启动界面打开
                            while (!startPlugin.IsShow)
                            {
                                Thread.Sleep(50);
                            }
                            loadedBundleCount++;
                            startPlugin.SetPercent(loadedBundleCount, bundleRuntime.Framework.Bundles.Count - 1, Name_ID[0]);
                        }
                        else
                        {
                            loadedBundleCount++;
                            startPlugin.SetPercent(loadedBundleCount, bundleRuntime.Framework.Bundles.Count - 1, Name_ID[0]);
                        }
                    }
                };
#if DEBUG
                v = true; //Kingo.PluginServiceInterface.Helper.AuthorizationVerification.ValidityLic(bundleRuntime, false, 6);
#else
                v = Kingo.PluginServiceInterface.Helper.AuthorizationVerification.ValidityLic(bundleRuntime, false, 6);
#endif
                if (!v)
                    return;
                //注册插件状态事件
                bundleRuntime.Framework.EventManager.AddBundleEventListener(bundleStateChangeEventHandler, true);
                //开始启动插件
                bundleRuntime.Start();
                //取消插件状态的事件
                bundleRuntime.Framework.EventManager.RemoveBundleEventListener(bundleStateChangeEventHandler, true);
                if (!v)
                {
                    GC.Collect();
                    Application.Exit();
                    return;
                }
                LogAPI.Debug("系统初始化...");
                //建库版本类型_GIS版本_授权类型_版本号_版本发布时间
                LogAPI.Debug($"{string.Format(ConfigurationManager.AppSettings.Get("VersionInformation"), GetArcGISVersion())}");
                #endregion
                var platform = bundleRuntime.GetFirstOrDefaultService();
                if (platform != null)
                {
                    Platform.Instance.Open();
                    platform.InitUI(null);
                    startPlugin?.CloseForm();
                    ExtensionShowWindow.MainWinForm = platform.Instance;
                    Platform.Instance.OutputMsg("系统初始化完成。");
                    Platform.Instance.UpdateStateBar("系统初始化完成");
                    WebsocketHelper.Instance.ConnectionCallback = (s) =>
                    {
                        WebsocketHelper.Instance.Conn = s as IWebSocketConnection;
                        {
                            (s as IWebSocketConnection).OnOpen = () => { };
                        }
                    };
                    WebsocketHelper.Instance.Start(7080);
                    Application.Run(platform.Instance);
                    RunIDService.Dispose();
                }
                else
                {
                    LogAPI.Debug("IPlatformService接口获取失败!");
                }
            }
        }
        /// 
        /// 获取ArcGSI版本
        /// 
        /// 
        static string GetArcGISVersion()
        {
            string registryKey64 = @"SOFTWARE\WOW6432Node\ESRI\ArcGIS 10.2 License Manager"; // 适用于64位系统
            string registryKey32 = @"SOFTWARE\ESRI\ArcGIS 10.2 License Manager";// 适用于32位系统
            string registryPath = Environment.Is64BitOperatingSystem ? registryKey64 : registryKey32;
            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryPath))
                {
                    if (key != null)
                    {
                        object realVersion = key.GetValue("RealVersion");//10.2.2
                        //realVersion = key.GetValue("Installer");  //"Administrator"
                        //realVersion = key.GetValue("ProductName");//ArcGIS 10.2.2 License Manager
                        if (realVersion.ToString() == "10.2.2")
                        {
                            return $"ArcGIS{realVersion}";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug($"获取ArcGIS版本错误:{ex.Message}");
            }
            return "AGVF";
        }
    }
}