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;

using DevExpress.Xpf.Editors.Settings;

namespace BeWo.View.Detail
{
	public partial class AdditionalServiceRegionView : BeWoView
	{
		private AdditionalServiceRegionListVM _ViewModel;

		public AdditionalServiceRegionView(AdditionalServiceRegionListVM pViewModel)
		{
			InitializeComponent();

			ColumnService.EditSettings = new ComboBoxEditSettings {ItemsSource = pViewModel.PossibleServices};

			ViewModel = pViewModel;
		}

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

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

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

		private AdditionalServiceRegionListVM ViewModel
		{
			get { return _ViewModel; }

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

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

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

			if (ViewModel.RemovedCount > 0)
			{
				lToDos.Add(s => s.DeactivateAdditionalServiceRegions(ViewModel.GetRemoved().ToDictionary(dc => dc.AdditionalServiceRegionOid.Value, dc => dc.AdditionalServiceRegionVersion.Value)));
			}

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

			ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, ReloadViewModel);
		}

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

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

		private void DeleteButton_Click(object sender, RoutedEventArgs e)
		{
			ViewModel.VMList.Remove(DatagridRegions.GetCurrentValue<AdditionalServiceRegionVM>());
			BeWoWpfUtils.RefreshDXGrid(DatagridRegions);
		}
	}
}