using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace MySQL
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            if (!File.Exists("my.ini"))
            {
                MessageBox.Show("请把程序放在正确的位置");
                Application.Exit();
            }
        }

        /// <summary>
        /// 一键修复
        /// </summary>
        private void Repair_Click(object sender, EventArgs e)
        {
            GetServer();//停止服务

            string path = Application.StartupPath.Replace("\\", "/") + "/";
            string myini = GetMyConfig.Getmy(path);

            File.Delete("my.ini");
            File.AppendAllText("my.ini", myini);

            MessageBox.Show("修复完成");
        }

        /// <summary>
        /// 启动/停止 服务
        /// </summary>
        private void Server_Click(object sender, EventArgs e)
        {
            int i = GetServer();
            if (i == 0)
            {
                try
                {
                    string path = Application.StartupPath + @"\bin\mysqld.exe";
                    Process.Start(path);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请不要擅自移动本程序的位置");
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("服务已停止");
            }
        }

        /// <summary>
        /// 启动/停止 服务
        /// </summary>
        /// <returns></returns>
        private int GetServer()
        {
            Process[] Process = System.Diagnostics.Process.GetProcesses();
            foreach (Process process in Process)
            {
                try
                {
                    string FileName = process.MainModule.FileName;
                    if (FileName.Contains("mysqld.exe"))
                    {
                        process.Kill();
                        return 1;
                    }
                }
                catch { }
            }
            return 0;
        }
    }
}