using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DBBackupTool.Data;
using DBBackupTool.Helpers;
using Microsoft.Win32;
using SqlSugar;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Windows;

namespace DBBackupTool.ViewModels;

public partial class DumpViewModel : ObservableObject
{
    public DumpViewModel()
    {
        this.DbInfo = new()
        {
            ServerAddress = "localhost",
            Port = 5432,
            User = "postgres",
            PassWord = "123456"
        };
        this.LoadingVis = Visibility.Collapsed;
    }

    private SqlSugarHelper? _dbHelper;

    [ObservableProperty]
    private Visibility _LoadingVis;

    [RelayCommand]
    private void CheckDB()
    {
        this.Tables ??= [];
        this.Tables.Clear();
        this.TableCount = 0;

        if (!CheckDBInfo())
        {
            MessageBox.Show("数据库信息不完整", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        _dbHelper = new();
        string dbString = $"Database={DbInfo.DataBase};Password={DbInfo.PassWord};Host={DbInfo.ServerAddress};Username={DbInfo.User};Persist Security Info=True";

        if (!_dbHelper.Open(dbString, SqlSugar.DbType.PostgreSQL, true) || _dbHelper.Client is null)
        {
            MessageBox.Show("数据库连接失败", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        IEnumerable<DbTableInfo> tables;
        try
        {
            tables = _dbHelper.Client.DbMaintenance.GetTableInfoList();
        }
        catch
        {
            MessageBox.Show("数据库不存在", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        this.Tables ??= [];
        this.Tables.Clear();
        foreach (DbTableInfo item in tables)
            this.Tables.Add(item);
        this.TableCount = this.Tables.Count;
        MessageBox.Show("数据库连接成功", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
    }

    [ObservableProperty]
    private DBInfo _dbInfo;

    [ObservableProperty]
    private ObservableCollection<DbTableInfo> _Tables = [];

    [ObservableProperty]
    private int _TableCount;

    [ObservableProperty]
    private string? _SavePath;

    [RelayCommand]
    private void Dump()
    {
        if (!CheckDBInfo())
        {
            MessageBox.Show("数据库信息不完整", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }
        if (string.IsNullOrEmpty(this.SavePath))
        {
            MessageBox.Show("选择保存路径", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }

        PostgreSQLTool tool = new();
        if (!tool.Initialize())
        {
            MessageBox.Show("PostgresSQL 未安装", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        this.LoadingVis = Visibility.Visible;
        Task.Factory.StartNew(() =>
        {
            Stopwatch sw = new();
            sw.Start();
            tool.BackUp(this.DbInfo.ServerAddress!, this.DbInfo.Port, this.DbInfo.User!, this.DbInfo.PassWord!, this.SavePath, this.DbInfo.DataBase!);
            if (!File.Exists(this.SavePath))
            {
                MessageBox.Show("备份失败", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            FileInfo file = new(this.SavePath);
            if (file.Directory is null)
                return;
            sw.Stop();
            MessageBox.Show($"备份完成,耗时 {sw.Elapsed.Seconds}s", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
            App.Current.Dispatcher.Invoke(() =>
            {
                this.LoadingVis = Visibility.Collapsed;

            });

            System.Diagnostics.Process.Start("Explorer.exe", file.Directory.FullName);
        });
    }

    [RelayCommand]
    private void SelectPath()
    {
        SaveFileDialog saveFileDialog = new()
        {
            Filter = "DumpFile|*.Custom;",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            FileName = $"{this.DbInfo.DataBase}_{DateTime.Now:yyMMdd_HHmmss}.Custom"
        };

        if (saveFileDialog.ShowDialog() != true)
            return;

        if (!saveFileDialog.FileName.EndsWith(".Custom"))
            saveFileDialog.FileName += ".Custom";

        SavePath = saveFileDialog.FileName; //获取选择的文件，或者自定义的文件名的全路径。
    }


    private bool CheckDBInfo()
    {
        if (this.DbInfo is null)
            return false;

        if (string.IsNullOrEmpty(DbInfo.ServerAddress))
            return false;

        if (string.IsNullOrEmpty(DbInfo.DataBase))
            return false;
        if (string.IsNullOrEmpty(DbInfo.User))
            return false;
        if (string.IsNullOrEmpty(DbInfo.PassWord))
            return false;
        return true;
    }
}
