using Microsoft.Win32.TaskScheduler;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Ursa.Controls;
using 常用工具集.Base;

namespace 常用工具集.ViewModel._04破解及系统相关
{
    public class MySQL定时备份ViewModel : ViewModelBase
    {
        public string FilePath { get; set; } = "";
        public string UserName { get; set; } = "root";
        public string Password { get; set; } = "root";
        public string DatabaseName { get; set; } = "test";
        public TimeSpan SelectedTime { get; set; } = TimeSpan.Zero;

        public string BackPath { get; set; } = "d:/test.sql";

        public DelegateCommand FindPathCmd { get; set; }
        public DelegateCommand CreateBackPlanCmd { get; set; }
        public MySQL定时备份ViewModel()
        {
            FindPathCmd = new DelegateCommand(FindPathCmdFunc);
            CreateBackPlanCmd = new DelegateCommand(CreateBackPlanCmdFunc);
        }

        private void FindPathCmdFunc(object obj)
        {
            try
            {
                Process process = Process.GetProcesses().Where(it => it.ProcessName.ToLower().Contains("mysql")).FirstOrDefault();
                if (process == null)
                {
                    MessageBox.ShowAsync("找不到MySQL安装路径");
                    return;
                }
                string path = process.MainModule.FileName;
                path = Directory.GetParent(path).FullName;
                FilePath = path;
            }
            catch
            {
                MessageBox.ShowAsync("找不到MySQL安装路径");
            }
        }

        private void CreateBackPlanCmdFunc(object obj)
        {
            string binPath = FilePath.Replace("\\", "/");
            if (string.IsNullOrEmpty(binPath))
            {
                MessageBox.ShowAsync("请输入mysqldump所在目录");
                return;
            }
            if (!binPath.EndsWith("/"))
            {
                binPath = binPath + "/";
            }
            if (!Directory.Exists(binPath))
            {
                MessageBox.ShowAsync("mysqldump所在目录不存在");
                return;
            }
            string userName = UserName;
            string password = Password;
            string dbName = DatabaseName;
            string backupFile = BackPath;

            string cmd = $"mysqldump -u {userName} -p{password} {dbName} > {backupFile}";
            string batPath = $"{dbName}_back.bat";
            File.WriteAllText(binPath + batPath, cmd);

            using (TaskService ts = new TaskService())
            {
                // 创建新的任务定义并指定任务的名称
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "MySQL定时备份";
                // 创建触发器，设置为每天的特定时间
                DailyTrigger dailyTrigger = new DailyTrigger();
                dailyTrigger.StartBoundary = DateTime.Today.Add(SelectedTime); //指定时间
                td.Triggers.Add(dailyTrigger);
                // 创建操作 - 运行一个程序
                td.Actions.Add(new ExecAction(batPath, "", binPath));
                // 注册任务到根文件夹下
                ts.RootFolder.RegisterTaskDefinition("MySQLBackup", td);
            }
            GlobalValues.Success("已创建备份计划");
        }
    }
}
