using FLY.Blowing.DbViewer.Core;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace FLY.Blowing.DbViewer
{
    /// <summary>
    /// PageSetup.xaml 的交互逻辑
    /// </summary>
    public partial class PageSetup : Page
    {
        PageSetupVm viewModel;
        public PageSetup()
        {
            InitializeComponent();

        }

        [Unity.InjectionMethod]
        public void Init(DbViewerModel dbViewerModel)
        {
            viewModel = new PageSetupVm();
            viewModel.Init(dbViewerModel);
            this.DataContext = viewModel;
        }

        private void ButtonBack_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
            this.NavigationService.RemoveBackEntry();
        }
    }

    public class PageSetupVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        public string DbDirPath { get; set; }
        
        public RelayCommand DbSelectCmd { get; private set; }


        public DbHelper DbHelper { get; } = new DbHelper();
        DbViewerModel dbViewerModel;
        public PageSetupVm()
        {
            DbSelectCmd = new RelayCommand(DbSelect);
        }

        public void Init(DbViewerModel dbViewerModel)
        {
            this.dbViewerModel = dbViewerModel;
            DbDirPath = dbViewerModel.DbDirPath;

            this.DbHelper.DbDirPath = DbDirPath;
            this.DbHelper.Init();
        }





        void DbSelect()
        {
            System.Windows.Forms.FolderBrowserDialog open = new System.Windows.Forms.FolderBrowserDialog();

            open.SelectedPath = DbDirPath;

            if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DbDirPath = open.SelectedPath;

                DbHelper.DbDirPath = DbDirPath;
                if (DbHelper.Init())
                {
                    dbViewerModel.DbDirPath = DbDirPath;
                    dbViewerModel.Save();
                    dbViewerModel.mDbHelper.DbDirPath = DbDirPath;
                    dbViewerModel.mDbHelper.Init();
                }
            }
        }
    }
}