﻿
using System;
using MvvmCross.Core.ViewModels;
using OpenLearningPlayer.Shared.Auxiliary.Logger;
using OpenLearningPlayer.Shared.DB;
using System.Collections.ObjectModel;
using EntityExtensionForORM;
using OpenLearningPlayer.Shared.Domain;

namespace OpenLearningPlayer.Shared.ViewModels
{
    public class SaveChanges_ViewModel : ViewModel_Base
    {
        ILogger Logger;
        INavigationService NavigationService;

        public ObservableCollection<Entity> Changes { get { return _Changes; } set { Set(ref _Changes, value); } } ObservableCollection<Entity> _Changes;

        public SaveChanges_ViewModel(ILogger Logger_, INavigationService NavigationService_)
        {
            if (!IsInDesignMode)
            {
                Logger = Logger_;
                NavigationService = NavigationService_;
                CommandDispatcher = new MvxCommand<string>(CmdDispatcher);
            }

            if (IsInDesignMode)
            {
                LearningItem li1 = new LearningItem { Name = "Mazzy" };
                LearningItem li2 = new LearningItem { Name = "Futurama" };

                Changes = new ObservableCollection<Entity>
                {
                    new Entity {
                        HardReference = li1,
                        Obj = new WeakReference<Base>(li1),
                        Order = 1,
                        State = Entity.EntityState.Added,
                        Type = li1.GetType()
                    },
                    new Entity {
                        HardReference = li2,
                        Obj = new WeakReference<Base>(li2),
                        Order = 2,
                        State = Entity.EntityState.Added,
                        Type = li1.GetType()
                    }
                };
            }

        }

        override public void OnNavigationOpenPage(ParametersOfForms param_)
        {
            SaveChanges_parameters param = (SaveChanges_parameters)param_;
            Changes = new ObservableCollection<Entity>(EFDbContext.Context.ChangedEntities);
        }

        public override void CmdDispatcher(string cmd)
        {
            switch (cmd)
            {
                case "Yes":
                    EFDbContext.SaveChgs();
                    FormResult = new SaveChanges_FormResult { isSaved = true };
                    NavigationService.NavigateBack();
                    break;

                case "No":
                    EFDbContext.Context.ClearChanges();
                    FormResult = new SaveChanges_FormResult { isSaved = false };
                    NavigationService.NavigateBack();
                    break;

                default:
                    throw new NotImplementedException();
            }
        }

    }
}
