using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DBBackupTool.Data;
using DBBackupTool.Helpers;
using Microsoft.Win32;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace DBBackupTool.ViewModels;

public partial class RestoreViewModel : ObservableObject
{
    public RestoreViewModel()
    {
        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;
        }

        _dbHelper.CreateTable(this.DbInfo.DataBase!);
        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 Restore()
    {
        this.Tables ??= [];
        this.Tables.Clear();

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

        if (_dbHelper is null || _dbHelper.Client is null)
        {
            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.Restore(this.DbInfo.ServerAddress!, this.DbInfo.Port, this.DbInfo.User!, this.DbInfo.PassWord!, this.SavePath, this.DbInfo.DataBase!);

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

            App.Current.Dispatcher.Invoke(() =>
            {
                this.Tables ??= [];
                this.Tables.Clear();
                foreach (DbTableInfo item in tables)
                    this.Tables.Add(item);
                this.TableCount = this.Tables.Count;
                this.LoadingVis = Visibility.Collapsed;
            });
            sw.Stop();

            MessageBox.Show($"还原完成,耗时 {sw.Elapsed.Seconds}s", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
        });

    }

    [RelayCommand]
    private void SelectPath()
    {
        OpenFileDialog dialog = new()
        {
            Filter = "DumpFile|*.Custom;",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        };

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


        SavePath = dialog.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;
    }
}
