using FLY.Thick.FilmCasting.UI.DbViewer.Db;
using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FLY.Thick.FilmCasting.UI.DbViewer
{
    /// <summary>
    /// DgSelectMonth.xaml 的交互逻辑
    /// </summary>
    public partial class DgSelectMonth : CustomDialog
    {
        DgSelectMonthVm viewModel;
        public DgSelectMonth()
        {
            InitializeComponent();
        }

        public void Init(DbHelper dbHelper)
        {
            viewModel = new DgSelectMonthVm();

            viewModel.Init(dbHelper);
            
            viewModel.AfterOk += ViewModel_AfterOk;
            this.DataContext = viewModel;
        }

        private async void ViewModel_AfterOk()
        {
            await App.MetroWindow.HideMetroDialogAsync(this);
        }

    }
    public class DgSelectMonthVm : INotifyPropertyChanged 
    {
        public bool IsRecent { get; set; }

        public ObservableCollection<string> MonthPaths { get; } = new ObservableCollection<string>();
        public string Selected { get; set; }

        public RelayCommand OkCmd { get; set; }
        public RelayCommand CancelCmd { get; set; }
        DbHelper dbHelper;
        public event Action AfterOk;
        public event PropertyChangedEventHandler PropertyChanged;

        public DgSelectMonthVm() {
            OkCmd = new RelayCommand(Ok);
            CancelCmd = new RelayCommand(() =>
            {
                AfterOk?.Invoke();
            });
        }



        public void Init(DbHelper dbHelper) 
        {
            this.dbHelper = dbHelper;
            Selected = this.dbHelper.MonthPath;
            IsRecent = string.IsNullOrEmpty(this.dbHelper.MonthPath);

            var list = this.dbHelper.GetMonthList();
            MonthPaths.Clear();
            for (int i = 0; i < list.Count(); i++) {
                MonthPaths.Add(list[i]);
            }
        }

        private void Ok()
        {
            if (IsRecent)
            {
                dbHelper.Init(dbHelper.DbDirPath, null);
            }
            else
            {
                dbHelper.Init(dbHelper.DbDirPath, Selected);
            }

            AfterOk?.Invoke();
        }
    
    }
}
