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

using BS.Shared.Extensions;

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

namespace BeWo.View.Detail
{
	public partial class AdditionalServiceAddView : BeWoView
	{
		private AdditionalServiceListVM _ViewModel;

		public AdditionalServiceAddView(AdditionalServiceListVM pViewModel)
		{
			InitializeComponent();
			ViewModel = pViewModel;
		}

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

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

		private AdditionalServiceListVM ViewModel
		{
			get { return _ViewModel; }

			set
			{
				_ViewModel = value;
				root.DataContext = value;
			}
		}

		// TODO
		internal override DependencyObject ValidationOnSaveRootElement
		{
			get { return button_addService; }
		}

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

			if (ViewModel.RemovedCount > 0)
			{
				lToDos.Add(s => s.DeactivateAdditionalServices(ViewModel.GetRemoved().ToDictionary(dc => dc.AdditionalServiceOid.Value, dc => dc.AdditionalServiceVersion.Value)));
			}

			if (ViewModel.AddedCount > 0)
			{
				lToDos.Add(s => s.InsertNewAdditionalServices(ViewModel.CommitAdded()));
			}

			if (ViewModel.ChangedCount > 0)
			{
				lToDos.Add(s => s.UpdateAdditionalServices(ViewModel.CommitChanged()));
			}

			ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, ReloadViewModel);
		}

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

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

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

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