using FLY.Thick.FilmCasting.UI.DbViewer.Core;
using FLY.Thick.FilmCasting.UI.DbViewer.Db;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace FLY.Thick.FilmCasting.UI.DbViewer
{
    /// <summary>
    /// PageSetup.xaml 的交互逻辑
    /// </summary>
    public partial class PgSetup : Page
    {
        PageSetupVm viewModel;
        public PgSetup()
        {
            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.Init(DbDirPath, null);
        }
        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;

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