using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;

namespace FrpcKeeper
{
    public partial class Form1 : UIForm
    {
        private static Mutex mutex = null;

        public Form1()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.FormBorderStyle = FormBorderStyle.None;
            this.ShowInTaskbar = false;
            this.WindowState = FormWindowState.Minimized;
            this.FormClosing += Form1_FormClosing;
            this.Resize += Form1_Resize;

            notifyIcon1 = new NotifyIcon
            {
                Icon = SystemIcons.Application, // 可以替换为你自己的图标
                Text = "Frpc Keeper",
                Visible = true
            };
            var contextMenu = new ContextMenuStrip();
            ToolStripMenuItem exitItem = new ToolStripMenuItem("退出", null, (s, e) => Application.Exit());
            contextMenu.Items.Add(new ToolStripSeparator());
            contextMenu.Items.Add(exitItem);
            notifyIcon1.ContextMenuStrip = contextMenu;
            notifyIcon1.MouseDoubleClick += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.BringToFront();
                    this.Activate();
                }
            };

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (IsAlreadyRunning())
            {
                MessageBox.Show("此程序已经在运行了", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
                return;
            }
            timer1.Start();
            timer1.Interval = 10000;

        }
        private bool IsAlreadyRunning()
        {
            bool createdNew;
            mutex = new Mutex(true, "Global\\FrpcKeeperMutex", out createdNew);
            if (!createdNew)
            {
                return true;
            }
            GC.KeepAlive(mutex); // 确保 Mutex 在程序退出时被释放
            return false;
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                this.WindowState = FormWindowState.Minimized;
            }
        }
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!Checkfrpcisrunning())
            {
                Runningfrpc(); 
            }
        }

        public static bool Checkfrpcisrunning()
        {
            try
            {
                Process[] processes = Process.GetProcessesByName("frpc");
                return processes.Length > 0;
            }
            catch 
            {
                return false;
            }
        }

        public static void Runningfrpc()
        {
            if (!Checkfrpcisrunning())
            {
                Logger.Log("检测到 frpc 未运行，开始执行启动操作");
                try
                {
                    string currentDir = AppDomain.CurrentDomain.BaseDirectory;
                    string batPath = Path.Combine(currentDir, "frpcstart.bat");

                    if (!File.Exists(batPath))
                    {
                        Logger.Log($"未找到 frpcstart.bat 在指定目录：{currentDir}");
                        return;
                    }

                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = batPath,
                        WorkingDirectory = currentDir,
                        UseShellExecute = false, // 不使用 shell 执行
                        CreateNoWindow = true,   // 不创建窗口
                        RedirectStandardOutput = true, // 重定向标准输出
                        RedirectStandardError = true   // 重定向错误输出
                    };

                    Process process = new Process { StartInfo = startInfo };
                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            Logger.Log($"[STDOUT] {e.Data}");
                        }
                    };

                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            Logger.Log($"[STDERR] {e.Data}");
                        }
                    };

                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    Logger.Log("启动操作已完成");
                }
                catch (Exception ex)
                {
                    Logger.Log($"执行启动操作失败: {ex.Message}");
                }
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string currentDir = AppDomain.CurrentDomain.BaseDirectory;
                string clientIniPath = Path.Combine(currentDir, "client.ini");
                if (!File.Exists(clientIniPath))
                {
                    MessageBox.Show("没有找到配置文件client.ini在指定目录：" + currentDir, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Process.Start(clientIniPath);    
            }
            catch (Exception ex)
            {
                Logger.Log("未能执行打开配置文件（非文件不存在）"+ex.Message);
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            Logger.Log("点击了了重启frpc的按钮");
            timer1.Stop(); 
            try
            {
                Process[] processes = Process.GetProcessesByName("frpc");
                foreach (Process process in processes)
                {
                    process.Kill(); 
                    process.WaitForExit(); 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("在执行结束frpc.exe进程时出错" + ex.Message,"错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Logger.Log("如未抛出异常，则已结束frpc进程");
            if (!Checkfrpcisrunning())
            {
                try
                {
                    timer1.Start();
                    Runningfrpc();
                    Logger.Log("如未抛出异常，则已重启frpc进程");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("在启动frpc时出错（timer1、Runningfrpc由重启button触发）" + ex.Message,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            Logger.Log("点击了释放资源的按钮");
            DialogResult result = MessageBox.Show(
                "如果已经释放过资源，资源将会被覆盖！",  // 提示信息
                "确认",               // 对话框标题
                MessageBoxButtons.YesNo,  // 按钮选项（是/否）
                MessageBoxIcon.Question   // 图标（问号）
            );
            if (result == DialogResult.No)
            {
                return; 
            }
            Assembly assembly = Assembly.GetExecutingAssembly();
            string[] resourceNames = {
               "FrpcKeeper.frpc.exe",
               "FrpcKeeper.client.ini",
               "FrpcKeeper.frpcstart.bat"
            };
            string[] newNames = {
                "frpc.exe",
                "client.ini",
                "frpcstart.bat"
            };
            try
            {
                for (int i = 0; i < resourceNames.Length; i++)
                {
                    using (Stream resourceStream = assembly.GetManifestResourceStream(resourceNames[i]))
                    {
                        if (resourceStream == null)
                        {
                            return;
                        }
                        string targetPath = Path.Combine(Application.StartupPath, newNames[i]);
                        using (FileStream fileStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write))
                        {
                            resourceStream.CopyTo(fileStream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Logger.Log("执行释放资源完成");
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            Logger.Log("点击了结束进程的按钮");
            timer1.Stop();
            try
            {
                Process[] processes = Process.GetProcessesByName("frpc");
                foreach (Process process in processes)
                {
                    process.Kill(); 
                    process.WaitForExit(); 
                    Logger.Log("执行结束frpc进程完成");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("在执行结束frpc.exe进程时出错" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }










    }  

