using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

using BS.Shared.Extensions;

namespace BeWo.View.Detail
{
	public partial class MedikamentenartenView
	{
		private MedArtListVM _ViewModel;
		public MedArtListVM ViewModel
		{
			get { return _ViewModel; }
			set
			{
				_ViewModel = value;
				root.DataContext = value;
			}
		}

		public override string Title
		{
			get { return "Medikamentenarten"; }
		}

		public override bool IsDirty
		{
			get { return ViewModel != null && ViewModel.IsDirty; }
		}

		public MedikamentenartenView(MedArtListVM pViewModel)
		{
			InitializeComponent();
			ViewModel = pViewModel;
		}

		private void ReloadViewModel()
		{
			VMFactory.CreateMedArtListVMAsync(r => this.Dispatch(delegate { ViewModel = r; }));
		}

		internal override DependencyObject ValidationOnSaveRootElement
		{
			get { return button_addMedArt; }
		}

		private void button_addMedArt_Click(object sender, RoutedEventArgs e)
		{
			if (ValidationTrigger.Validate(this))
				ViewModel.AddNewVMToList();
		}

		private void DeleteButton_Click(object sender, RoutedEventArgs e)
		{
			var lVM = DatagridServices.GetCurrentValue<MedArtVM>();
			if (lVM == null) return;

			ViewModel.VMList.Remove(lVM);
			BeWoWpfUtils.RefreshDXGrid(DatagridServices);
		}

		protected override void Save()
		{
			var lToDos = new List<Action<ICustomerService>>();

			if(ViewModel.RemovedCount > 0)
				lToDos.Add(s=>s.DeleteMedArten(ViewModel.GetRemoved().ToDictionary(dc => dc.MedArtOid.Value, dc => dc.MedArtVersion.Value)));
			if (ViewModel.AddedCount > 0)
				lToDos.Add(s => s.InsertMedArten(ViewModel.CommitAdded()));
			if (ViewModel.ChangedCount > 0)
				lToDos.Add(s => s.UpdateMedArten(ViewModel.CommitChanged()));

			ServiceFacade.DoMultipleCustomerServicesAsync(lToDos, ReloadViewModel);
		}
	}
}
