using BPA.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using BPA.Model;
using BPA.SingleDevice.Helper;
using BPA.Model.Table;

namespace BPA.SingleDevice.ViewModel
{
    public class NewRecipeViewModel : NotifyBase, IDialogDataContext
    {
        public NewRecipeViewModel()
        {

            SqlHelper.GetInstance.GetListAsync<RawMaterTB>().Result.OnSuccess(s =>
            {
                s.ForEach(item =>
                {
                    NewRecipeModels.Add(new NewRecipeModel() { Name = item.Name, Id = item.Id });
                });
            });

            SaveCommand = new BPARelayCommand(() =>
            {
                var result = new Parameters();
                result.Add("Name", RecipeName);
                result.Add("RawMater", NewRecipeModels.Where(p => p.IsChecked == true).ToList());
                RequestClose?.Invoke(result);
            });
            CancelCommand = new BPARelayCommand(() => { RequestClose?.Invoke(null); });
        }

        public string Title => "";

        public event Action<object> RequestClose;
        public void OnDialogOpened(object parameters)
        {
            if (parameters is Parameters par)
            {
                if (par.TryGetValue("Name", out string name) && par.TryGetValue("RawMater", out List<NewRecipeModel> rms))
                {
                    RecipeName = name;
                    rms.ForEach(item =>
                    {
                        var res = NewRecipeModels.FirstOrDefault(p => p.Id == item.Id);
                        if (res != null)
                        {
                            res.Weight = item.Weight;
                            res.IsChecked = true;
                        }
                    });
                }
            }
        }

        public ObservableCollection<NewRecipeModel> NewRecipeModels { get; set; } = new ObservableCollection<NewRecipeModel>();

        public string RecipeName { get { return _mRecipeName; } set { _mRecipeName = value; OnPropertyChanged(); } }
        private string _mRecipeName;

        public BPARelayCommand SaveCommand { get; set; }

        public BPARelayCommand CancelCommand { get; set; }
    }
}
