using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using BS.Shared;
using BS.Shared.Extensions;

using BeWo.ServiceProxy;
using BeWo.View.Detail;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

namespace BeWo.View.Master
{
	public partial class AdministrationView
	{
		private readonly Dictionary<TabItem, BeWoView> _OpenViews = new Dictionary<TabItem, BeWoView>();

		private bool _SavePerformed;

		public AdministrationView()
		{
			InitializeComponent();

			// HACK: Force the devexpress grid to end editing when the mouse is over savebutton
			// by setting the focus to another element. 
			MouseMove += (s, e) =>
				             {
					             Point p = e.GetPosition(btnSave);

					             if (p.X >= 0 && p.X < btnSave.ActualWidth && p.Y >= 0 && p.Y < btnSave.ActualHeight)
					             {
						             root.Focus();
					             }
				             };

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_View))
			{
				tabitem_assessmentSheetValues.Visibility = Visibility.Collapsed;
				tabitem_assessmentSheetCategories.Visibility = Visibility.Collapsed;
			}

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.AdditionalService_View))
			{
				tabitem_additionalServices.Visibility = Visibility.Collapsed;
				tabitem_additionalServiceRegions.Visibility = Visibility.Collapsed;
			}

			tabitem_auszahlungsarten.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.OvertimeView) ? Visibility.Visible : Visibility.Collapsed;

			if (!BeWoApp.AppSettings.IsMedicationAllowed)
			{
				tabitem_medikamentenarten.Visibility = Visibility.Collapsed;
			}
		}

		public override bool IsDirty
		{
			get
			{
			    return _OpenViews.ContainsKey(root.SelectedItem as TabItem) && _OpenViews[root.SelectedItem as TabItem].IsDirty;
			}
		}

		internal override DependencyObject ValidationOnSaveRootElement
		{
			get { return _OpenViews[root.SelectedItem as TabItem].ValidationOnSaveRootElement; }
		}

		internal override bool DoSaveCheck()
		{
			var item = root.SelectedItem as TabItem;
			if (item != null && _OpenViews.ContainsKey(item))
			{
				var lDoSave = _OpenViews[root.SelectedItem as TabItem].DoSaveCheck();

				if (lDoSave && IsDirty)
				{
					_SavePerformed = true;
					_OpenViews.Remove(root.SelectedItem as TabItem);
				}

				return lDoSave;
			}

			return true;
		}

		protected override void Save()
		{
			_OpenViews[root.SelectedItem as TabItem].SaveData();
			_SavePerformed = true;
		}

		private void AddView(TabItem pTabItem, BeWoView pView)
		{
			_OpenViews[pTabItem]    = pView;
			pTabItem.Content        = pView;
			pView.VerticalAlignment = VerticalAlignment.Top;
			
			if (ActualHeight > 120)
			{
			    pView.MaxHeight = ActualHeight - 120;
			}

			_SavePerformed = false;
		}

		private void root_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			var lTabItem = e.Source as TabItem;
			if (lTabItem == null || Equals(root.SelectedItem, lTabItem))
			{
				return;
			}

			if (_OpenViews[root.SelectedItem as TabItem].IsDirty)
			{
				if (DoSaveCheck())
				{
					lTabItem.IsSelected = true;
				}
				else
				{
					e.Handled = true;
				}
			}
		}

		//private void tabitem_InvoiceNumber_Selected(object sender, RoutedEventArgs e)
		//{
		//    if (!this._OpenViews.ContainsKey(this.tabitem_InvoiceNumber) || this._SavePerformed)
		//    {
		//        VMFactory.CreateInvoiceNumberVMAsync(r => this.Dispatch(delegate { this.AddView(this.tabitem_InvoiceNumber, new InvoiceNumberView(r)); }));
		//    }
		//}

		private void tabitem_absenceCategories_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_absenceCategories) || _SavePerformed)
			{
				VMFactory.CreateAbsenceReasonListVMAsync(r => this.Dispatch(() => AddView(tabitem_absenceCategories, new AbsenceReasonView(r))));
			}
		}

		private void tabitem_activityFocus_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_activityFocus) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.StaffActivityFocusType, r => this.Dispatch(() => AddView(tabitem_activityFocus, new ValueListView(r))));
			}
		}

		private void tabitem_assessmentSheetCategories_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_assessmentSheetCategories) || _SavePerformed)
			{
				VMFactory.CreateAssessmentSheetCategoryListVM(m => this.Dispatch(() => AddView(tabitem_assessmentSheetCategories, new AssessmentSheetCategoryView(m))));
			}
		}

		private void tabitem_assessmentSheetValues_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_assessmentSheetValues) || _SavePerformed)
			{
				VMFactory.CreateAssessmentSheetValueListVM(m => this.Dispatch(() => AddView(tabitem_assessmentSheetValues, new AssessmentSheetValueView(m))));
			}
		}

		private void tabitem_customerCareTypes_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_customerCareTypes) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.CustomerCareType, r => this.Dispatch(() => AddView(tabitem_customerCareTypes, new ValueListView(r))));
			}
		}

		private void tabitem_disablityTypes_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_disablityTypes) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.DisabilityType, r => this.Dispatch(() => AddView(tabitem_disablityTypes, new ValueListView(r))));
			}
		}

		private void tabitem_employmentTypes_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_employmentTypes) || _SavePerformed)
			{
				VMFactory.CreateEmploymentTypeListVMAsync(r => this.Dispatch(() => AddView(tabitem_employmentTypes, new EmploymentTypeView(r))));
			}
		}

		private void tabitem_environmentRoles_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_environmentRoles) || _SavePerformed)
			{
				//VMFactory.CreateValueListVMAsync(ValueListEntryType.EnvironmentPersonType, r => this.Dispatch(delegate { this.AddView(this.tabitem_environmentRoles, new ValueListView(r)); }));

				VMFactory.CreateValueListVMAsync(ValueListEntryType.EnvironmentPersonType,
				                                 personList => VMFactory.CreateValueListVMAsync(ValueListEntryType.EnvironmentOrganisationType,
				                                                                                orgList =>
				                                                                                this.Dispatch(() => AddView(tabitem_environmentRoles, new EnvironmentRoleView(personList, orgList)))));
			}
		}

		private void tabitem_finazCategories_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_finazCategories) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.AccountingTransactionType, r => this.Dispatch(() => AddView(tabitem_finazCategories, new ValueListView(r))));
			}
		}

		private void tabitem_functions_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_functions) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.FunctionType, r => this.Dispatch(() => AddView(tabitem_functions, new ValueListView(r))));
			}
		}

		private void tabitem_goalcategories_Selected(object sender, RoutedEventArgs e) // Ziele und Maßnahmen
		{
			if (!_OpenViews.ContainsKey(tabitem_goalcategories) || _SavePerformed)
			{
				VMFactory.CreateGoalCategoryVMAsync(r => this.Dispatch(() => AddView(tabitem_goalcategories, new MassnahmenTreeViewView(r))));
			}
		}

		private void tabitem_goals_Selected(object sender, RoutedEventArgs e)
		{
			//if (!_OpenViews.ContainsKey(tabitem_goals) || _SavePerformed)
			//{
			//	VMFactory.CreateSupportConceptGoalListVMAsync(
			//		ValueListEntryType.SupportConceptGoalType,
			//		ValueListEntryType.SupportConceptGoalCategoryType,
			//		r => this.Dispatch(() => AddView(tabitem_goals, new SupportConceptGoalView(r))));
			//}
		}

		private void tabitem_mandator_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_mandator) || _SavePerformed)
			{
				ServiceFacade.DoAccountingServiceAsync(s => s.LoadInvoiceNumber(),
				                                       iv => ServiceFacade.DoOperationsServiceAsync(
					                                       s => s.GetMandator(),
					                                       m =>
					                                       this.Dispatch(() => AddView(tabitem_mandator, new MandatorView(new MandatorVM(new InvoiceNumberVM(iv), m))))));
			}
		}


		//SCHEDULER
        private void tabitem_schedulerSettings_Selected(object sender, RoutedEventArgs e)
        {
			//### CB
			//if (!this._OpenViews.ContainsKey(this.tabitem_schedulerSettings) || this._SavePerformed)
			//{
			//	VMFactory.CreateAppointmentCategoryListVMAsync(r => this.Dispatch(delegate { this.AddView(this.tabitem_schedulerSettings, new SchedulerSettingsView(r)); }));
			//}
        }


		private void tabitem_news_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_news) || _SavePerformed)
			{
				ServiceFacade.DoEmployeeServiceAsync(s => s.GetAllNewsItems(), cb => this.Dispatch(() => AddView(tabitem_news, new NewsItemView(new NewsItemListVM(cb)))));
			}
		}

		private void tabitem_placementObjectives_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_placementObjectives) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.PlacementObjectiveType, r => this.Dispatch(() => AddView(tabitem_placementObjectives, new ValueListView(r))));
			}
		}

		private void tabitem_qualificationTypes_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_qualificationTypes) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.StaffQualificationsType, r => this.Dispatch(() => AddView(tabitem_qualificationTypes, new ValueListView(r))));
			}
		}

		private void tabitem_resourceCategories_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_resourceCategories) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.ResourceCategory, r => this.Dispatch(() => AddView(tabitem_resourceCategories, new ValueListView(r))));
			}
		}

		private void tabitem_resources_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_resources) || _SavePerformed)
			{
				VMFactory.CreateResourceListVMAsync(r => this.Dispatch(() => AddView(tabitem_resources, new RessourceView(r))));
			}
		}

		private void tabitem_roles_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_roles) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.StaffRoleType, r => this.Dispatch(() => AddView(tabitem_roles, new ValueListView(r))));
			}
		}

		private void tabitem_serviceCategories_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_serviceCategories) || _SavePerformed)
			{
				VMFactory.CreateServiceCategoryListVMAsync(r => this.Dispatch(() => AddView(tabitem_serviceCategories, new ServiceCategoryView(r))));
			}
		}

		private void tabitem_serviceDescriptions_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_serviceDescriptions) || _SavePerformed)
			{
				VMFactory.CreateServiceDescriptionListVMAsync(r => this.Dispatch(() => AddView(tabitem_serviceDescriptions, new ServiceDescriptionView(r))));
			}
		}

		private void tabitem_terminationReasons_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_terminationReasons) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.TerminationReasonType, r => this.Dispatch(() => AddView(tabitem_terminationReasons, new ValueListView(r))));
			}
		}

		private void tabitem_titles_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_titles) || _SavePerformed)
			{
				VMFactory.CreateValueListVMAsync(ValueListEntryType.TitleType, r => this.Dispatch(() => AddView(tabitem_titles, new ValueListView(r))));
			}
		}

		private void Tabitem_additionalServiceRegions_OnSelected(object sender, RoutedEventArgs e)
		{
            if (!_OpenViews.ContainsKey(tabitem_additionalServiceRegions) || _SavePerformed)
            {
                VMFactory.CreateAdditionalServiceRegionListVMAsync(r => this.Dispatch(() => AddView(tabitem_additionalServiceRegions, new AdditionalServiceRegionView(r))));
            }
		}

		private void Tabitem_additionalAdditionalServices_OnSelected(object sender, RoutedEventArgs e)
		{
            if (!_OpenViews.ContainsKey(tabitem_additionalServices) || _SavePerformed)
            {
                VMFactory.CreateAdditionalServiceListVMAsync(r => this.Dispatch(() => AddView(tabitem_additionalServices, new AdditionalServiceAddView(r))));
            }
		}

		private void Tabitem_auszahlungsarten_OnSelected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_auszahlungsarten) || _SavePerformed)
			{
				VMFactory.CreateAuszahlungsartenListVMAsync(r => this.Dispatch(() => AddView(tabitem_auszahlungsarten, new AuszahlungsartenAddView(r))));
			}
		}

		private void tabitem_medikamentenarten_Selected(object sender, RoutedEventArgs e)
		{
			if (!_OpenViews.ContainsKey(tabitem_medikamentenarten) || _SavePerformed)
				VMFactory.CreateMedArtListVMAsync(r => this.Dispatch(() => AddView(tabitem_medikamentenarten, new MedikamentenartenView(r))));
		}

	    private void tabitem_textbausteine_Selected(object sender, RoutedEventArgs e)
	    {
            if (!_OpenViews.ContainsKey(tabitem_textbausteine) || _SavePerformed)
            {
                VMFactory.CreateTextbausteinListVMAsync(r => this.Dispatch(() => AddView(tabitem_textbausteine, new TextbausteinView(r, true))), true);
            }
	    }

        private void tabitem_dokumenttype_Selected(object sender, RoutedEventArgs e)
        {
            if (!_OpenViews.ContainsKey(tabitem_dokumenttype) || _SavePerformed)
            {
                VMFactory.CreateValueListVMAsync(ValueListEntryType.DocumentType, r => this.Dispatch(() => AddView(tabitem_dokumenttype, new DokumentationstypView(r))));
            }
        }
	}
}