using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Windows;

namespace SWRIS.Extensions
{
    /// <summary>
    /// 单实例应用程序管理器
    /// </summary>
    public class SingleInstanceManager
    {
        private readonly string _mutexName;
        private readonly string _applicationName;
        private Mutex _mutex;

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(IntPtr hWnd);

        // Window show commands
        private const int SW_HIDE = 0;
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;
        private const int SW_SHOWNOACTIVATE = 4;
        private const int SW_RESTORE = 9;

        /// <summary>
        /// 当需要激活已有实例时触发
        /// </summary>
        public event Action<Process> InstanceActivated;

        /// <summary>
        /// 初始化单实例管理器
        /// </summary>
        /// <param name="applicationName">应用程序唯一名称</param>
        public SingleInstanceManager(string applicationName)
        {
            _applicationName = applicationName ?? throw new ArgumentNullException(nameof(applicationName));
            _mutexName = $@"Global\{applicationName}";
        }

        /// <summary>
        /// 检查是否已是运行实例
        /// </summary>
        /// <returns>true表示已有实例运行，false表示这是第一个实例</returns>
        public bool IsAlreadyRunning()
        {
            try
            {
                _mutex = new Mutex(true, _mutexName, out bool createdNew);
                return !createdNew;
            }
            catch (Exception ex)
            {
                // 记录日志或处理异常
                Debug.WriteLine($"Mutex创建失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 切换到已有运行实例
        /// </summary>
        /// <returns>true表示成功切换到已有实例，false表示切换失败</returns>
        public bool SwitchToExistingInstance()
        {
            try
            {
                Process currentProcess = Process.GetCurrentProcess();
                Process existingProcess = FindExistingProcess(currentProcess);

                if (existingProcess != null && existingProcess.MainWindowHandle != IntPtr.Zero)
                {
                    ActivateProcessWindow(existingProcess);
                    InstanceActivated?.Invoke(existingProcess);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"切换到已有实例失败: {ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 切换到已有运行实例
        /// </summary>
        /// <returns>true表示成功切换到已有实例，false表示切换失败</returns>
        public bool SwitchToExistingInstance(string processName)
        {
            try
            {
                Process existingProcess = Process.GetProcessesByName(processName).FirstOrDefault();
                if (existingProcess != null && existingProcess.MainWindowHandle != IntPtr.Zero)
                {
                    ActivateProcessWindow(existingProcess);
                    InstanceActivated?.Invoke(existingProcess);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"切换到已有实例失败: {ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 查找已有的应用程序进程
        /// </summary>
        private Process FindExistingProcess(Process currentProcess)
        {
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);

            foreach (Process process in processes)
            {
                if (process.Id != currentProcess.Id &&
                    !process.HasExited &&
                    process.MainWindowHandle != IntPtr.Zero)
                {
                    return process;
                }
            }

            return null;
        }

        /// <summary>
        /// 激活进程窗口
        /// </summary>
        private void ActivateProcessWindow(Process process)
        {
            IntPtr mainWindowHandle = process.MainWindowHandle;

            if (IsIconic(mainWindowHandle))
            {
                ShowWindow(mainWindowHandle, SW_RESTORE);
            }

            SetForegroundWindow(mainWindowHandle);

            // 如果窗口不可见，尝试显示它
            if (!IsWindowVisible(mainWindowHandle))
            {
                ShowWindow(mainWindowHandle, SW_SHOWNORMAL);
            }
        }

        /// <summary>
        /// 激活当前应用程序的主窗口
        /// </summary>
        public void ActivateCurrentApplication()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Window mainWindow = Application.Current.MainWindow;

                if (mainWindow != null)
                {
                    if (mainWindow.WindowState == WindowState.Minimized)
                    {
                        mainWindow.WindowState = WindowState.Normal;
                    }

                    mainWindow.Show();
                    mainWindow.Activate();
                    mainWindow.Topmost = true;
                    mainWindow.Topmost = false;
                    mainWindow.Focus();
                }
            });
        }
 
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _mutex?.Dispose();
            _mutex = null;
        }
    }
}