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

using BeWo.Controls;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.View.Search;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;
using BeWo.Core.Service;

using BS.Shared;
using BS.Shared.Extensions;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Services;

namespace BeWo.View.Detail
{
    public partial class ServiceRecordEditView
    {
        private FlatSupportConceptTreeNodeDC _OriginalNode;

		private ServiceCategoryDC _OldCategory;

		private ServiceDescriptionDC _OldServiceDescription;

        private ServiceRecordVM _ServiceRecordVM;

        private CompactEmployeeDC _SelectedEmployee;

        private bool _HideCustomers;

        public ServiceRecordEditView()
        {
            InitializeComponent();
        }

        public override bool CanDelete
        {
            get
            {
                return false;
            }
        }

        public override bool IsDirty
        {
            get
            {
				
                //if (ViewModel.SelectedVMForEditing != null && _SelectedEmployee != null &&
                //    !_SelectedEmployee.Equals(ViewModel.SelectedVMForEditing.Employee))
                //    return true;

				return _ServiceRecordVM != null && _ServiceRecordVM.IsDirty;
            }
        }

        public override string SaveObjectName
        {
            get
            {
                return "dieser Leistungsbuchung";
            }
        }

        public override string Title
        {
            get
            {
                return "Leistungsbuchung bearbeiten";
            }
        }

        public ServiceRecordListVM ViewModel { get; set; }

        public void InitView(ServiceRecordListVM pListViewModel, ServiceRecordVM pSCViewModel, bool hideCustomerCombo)
        {
            InitializeComponent();
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherTeamMember))
            {
                lblEmployee.Visibility = Visibility.Collapsed;
                popupedit_employee.Visibility = Visibility.Collapsed;
            }
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees))
                employeeSearchView.SearchMode = SearchMode.OnlyTeamMember;

			numerictb_distance.Visibility = BeWoApp.AppSettings.ShowDistanceFields ? Visibility.Visible : Visibility.Collapsed;
			lblDistance.Visibility = BeWoApp.AppSettings.ShowDistanceFields ? Visibility.Visible : Visibility.Collapsed;

            _HideCustomers = hideCustomerCombo;
            _ServiceRecordVM = pSCViewModel;
			
            //ServiceRecordVM clone = pSCViewModel.Clone();

            //clone.Category2Services = pListViewModel.PrototypeVM.Category2Services;
			_OldCategory = _ServiceRecordVM.Category;
			_OldServiceDescription = _ServiceRecordVM.ServiceDescription;

            //_SelectedEmployee = clone.Employee;

			DataContext = _ServiceRecordVM;

			if (_ServiceRecordVM.Employee != null)
				popupedit_employee.Text = _ServiceRecordVM.Employee.ToString();

			if (!hideCustomerCombo)
			{
				FlatSupportConceptTreeNodeDC node = SupportConceptService.CreateFlatSupportConceptItem(pSCViewModel.SupportConcept, pSCViewModel.CostBearer);
				_OriginalNode = node;
				_ServiceRecordVM.ChoosenNode = node;
				supportConceptSelectionControl.SearchText = node.CustomerName;
			}

			if (BeWoApp.AppSettings.ShowMarker)
			{
				chkServiceRecordTypeContent.Content = "Marker";
				chkServiceRecordTypeContent.Visibility = Visibility.Visible;

			}
			else
			{
				if (BeWoApp.Mandator.BeWoClientType == 3)
				{
					//Köln Ring
					chkServiceRecordTypeContent.Visibility = Visibility.Visible;
				}
				else
				{
					chkServiceRecordTypeContent.Visibility = Visibility.Collapsed;
				}
			}

            //pListViewModel.SelectedVMForEditing = clone;
            ViewModel = pListViewModel;

            if (!hideCustomerCombo)
            {
                supportConceptSelectionControl.Loaded += (s, e) => SetSelectedCustomerNode();

                combobox_services.SelectionChanged += (s, e) =>
                    {
                        if (combobox_services.SelectedIndex == -1)
                            combobox_services.SelectedIndex = 0;
                    };
            }
            else
            {
                supportConceptSelectionControl.Visibility = Visibility.Collapsed;
                customerComboColumn.Width = new GridLength(0);
            }

            Focus();
            TextboxNotice.Focus();
            
            ComboBoxTreeViewControl.TreeViewSourceList = _ServiceRecordVM.GoalTree;
			ComboBoxTreeViewControl.Visibility = (_ServiceRecordVM.IsGoalTreeVisible) ? Visibility.Visible : Visibility.Collapsed;
            Loaded += ServiceRecordEditView_Loaded;

            ConfigureDocTypes();
            isEndDateVisible();
        }

        private void isEndDateVisible()
        {

            var Settings = BeWoApp.AppSettings;

            if (Settings.IsEndDateVisible)
            {

                datepicker_newEndDate.Visibility = Visibility.Visible;
                EndDateLabel.Visibility = Visibility.Visible;
            }
            else
            {
                datepicker_newEndDate.Visibility = Visibility.Collapsed;
                EndDateLabel.Visibility = Visibility.Collapsed;       
            }

        }

        public bool IsCustomerChangeAllowed()
        {
			//FlatSupportConceptTreeNodeDC selectedNode = _ServiceRecordVM.ChoosenNode;

            bool lAllowed = true;

			if (_OriginalNode != null)
			{
				if (_ServiceRecordVM.Customer != null && _OriginalNode.SupportConceptTreeNodeDC.Customer != null && _ServiceRecordVM.Customer.CustomerOid != _OriginalNode.SupportConceptTreeNodeDC.Customer.CustomerOid)
				{
					if (MessageBox.Show("Möchten Sie diese Leistung wirklich auf Klient " + _ServiceRecordVM.Customer.FirstName + " " + _ServiceRecordVM.Customer.LastName + " umbuchen?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
						lAllowed = false;
				}
				else if (_ServiceRecordVM.SupportConcept != null && _OriginalNode.SupportConceptTreeNodeDC.SupportConcept != null && _ServiceRecordVM.SupportConcept.SupportConceptOid != _OriginalNode.SupportConceptTreeNodeDC.SupportConcept.SupportConceptOid)
				{
					if (MessageBox.Show("Möchten Sie diese Leistung wirklich auf einen anderen Hilfeplan umbuchen?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
						lAllowed = false;
				}
				else if (_ServiceRecordVM.CostBearer != null && _OriginalNode.SupportConceptTreeNodeDC.CostBearer != null && _ServiceRecordVM.CostBearer.CostBearerOid != _OriginalNode.SupportConceptTreeNodeDC.CostBearer.CostBearerOid)
				{
					if (MessageBox.Show("Möchten Sie diese Leistung wirklich auf den Kostenträger " + _ServiceRecordVM.CostBearer.Name + " umbuchen?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
						lAllowed = false;
				}
			}
            return lAllowed;
        }

        public bool IsValid()
        {
			FlatSupportConceptTreeNodeDC selectedNode = _ServiceRecordVM.ChoosenNode;

            bool lValid = !(!_HideCustomers && selectedNode == null);

			lValid = ValidationTrigger.Validate(rootGrid) && lValid;

	        if (lValid)
	        {
				lValid = BeWoUtils.ValidateServiceRecordVM(_ServiceRecordVM, ViewModel.StatisticsDC, _ServiceRecordVM.ChoosenNode, false, _ServiceRecordVM.Employee, null, null);
				
	        }
	        return lValid;
        }

        internal override bool DoSaveCheck()
        {
            if (IsDirty)
            {
                MessageBoxResult lResult = ShowSaveQuestion();
                if (lResult == MessageBoxResult.Cancel)
                {
                    Focus();
                    return false;
                }

                if (lResult == MessageBoxResult.Yes)
                {
                    if (!IsCustomerChangeAllowed())
                        return false;

                    SaveData();
                }
            }

            return true;
        }

        protected override void Save()
        {
            if (IsDirty)
            {
                //var valid = ServiceFacade.DoOperationsServiceSync(s => s.CheckExistingSettlementInvoices(_OriginalVM.CommitToDataContract()));

				//if (valid.Contains(ServiceRecordValidationResult.SettlementInvoiceAlreadyExisting))
				//{
				//	MessageBox.Show("Es existiert bereits eine Spitzabrechnung. Um die Änderungen zu berücksichtigen muss gegebenenfalls eine neue Spitzabrechnung erstellt werden.",
				//					"Speichern", MessageBoxButton.OK, MessageBoxImage.Warning);
				//	//return;
				//}

                //ViewModel.SelectedVMForEditing.CopyTo(_OriginalVM);

				
                //if (!_HideCustomers)
				//	_ServiceRecordVM.ChoosenNode = _SelectedNode;

				if (!_HideCustomers && _ServiceRecordVM.ServiceDescription.Category != null && _ServiceRecordVM.ServiceDescription.Category.IsBillable && _ServiceRecordVM.ChoosenNode.SupportConceptTreeNodeDC.CostBearer != null)
                {

					Calculations calc = Calculations.GetInstance(_ServiceRecordVM.ChoosenNode.SupportConceptTreeNodeDC.CostBearer.CostBearerID);
					var roundedDuration = calc.GetRoundedDuration(
						_ServiceRecordVM.ChoosenNode.SupportConceptTreeNodeDC.CostBearer.ActualMinuteIntervall,
						_ServiceRecordVM.Duration.Value);

					_ServiceRecordVM.RoundedDuration = roundedDuration;
                    
                }
                else
                {
					_ServiceRecordVM.RoundedDuration = _ServiceRecordVM.Duration.Value;
                }

                if (_SelectedEmployee != null)
					_ServiceRecordVM.Employee = _SelectedEmployee;

				ServiceRecordDC lDC = _ServiceRecordVM.CommitToDataContract();

                if (!_HideCustomers)
					if (_ServiceRecordVM.ChoosenNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC != null)
						lDC.CostBearer2SupportConceptOid = _ServiceRecordVM.ChoosenNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid;

                var list = new List<ServiceRecordDC> {lDC};

                ServiceFacade.DoOperationsServiceSync(s => s.UpdateServiceRecords(list));
	            
            }
        }

        private void EmployeeSearchView_CustomerSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            _ServiceRecordVM.Employee = e.Data;
			popupedit_employee.Text = _ServiceRecordVM.Employee.ToString();
            popup_employee.IsOpen = false;
        }

        private void ServiceRecordEditView_Loaded(object sender, RoutedEventArgs e)
        {
			_ServiceRecordVM.Category = _OldCategory;
			_ServiceRecordVM.ServiceDescription = _OldServiceDescription;
			_ServiceRecordVM.SetDirty(false);
	        if (ActualHeight > 0)
	        {
		        ComboBoxTreeViewControl.ParentWindowHeight = ActualHeight;
	        }
	        ComboBoxTreeViewControl.Imitationheader.Width = 194;
        }

        private void SetSelectedCustomerNode()
        {
            supportConceptSelectionControl.SelectedItem = _OriginalNode;

            //ViewModel.SelectedVMForEditing.ChoosenNode = _SelectedNode;
        }

        private void supportConceptSelectionControl_ItemSelected(object sender, EventArgs<FlatSupportConceptTreeNodeDC> e)
        {
            if (!_HideCustomers)
            {
				_ServiceRecordVM.ChoosenNode = e.Data;
                //if (selectedNode != null && ViewModel != null)
                //    ViewModel.SelectedVMForEditing.ChoosenNode = selectedNode;
            }
        }

        private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_employee.IsOpen = true;
        }

        private void Popupedit_employee_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || _SelectedEmployee == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }
            
            VMFactory.CreateEmployeeVMAsync(_SelectedEmployee.EmployeeOid,
                cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, ServiceRecordEditView>(cb, this, () => this.Dispatch(
                        delegate
                            {
                                ServiceFacade.DoEmployeeServiceSync(s => _SelectedEmployee = s.LoadCompactEmployee(_SelectedEmployee.EmployeeOid));
                                BeWoUtils.UpdateSearchViewObjectList(employeeSearchView, _SelectedEmployee);
                                popupedit_employee.Text = _SelectedEmployee.ToString();

                                BeWoUtils.UpdateAllViews(_SelectedEmployee);
                            }
                    ))));
        }

        private void ConfigureDocTypes()
        {
            //Tabs und Tabelle
            int i = ViewModel.AllDocTypes.Count;

            if (i == 0)
            {
                TabItem1_Notice.Header = "Dokumentation";
                TabItem2_Notice.Visibility = Visibility.Collapsed;
                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

            }
            else if (i == 1)
            {
                TabItem1_Notice.Header = ViewModel.AllDocTypes[0].ToString();            

                TabItem2_Notice.Visibility = Visibility.Collapsed;
                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

            }
            else if (i == 2)
            {
                TabItem1_Notice.Header = ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = ViewModel.AllDocTypes[1].ToString();

                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;
              
            }
            else if (i == 3)
            {
                TabItem1_Notice.Header = ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = ViewModel.AllDocTypes[2].ToString();

                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

            }
            else if (i == 4)
            {
                TabItem1_Notice.Header = ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = ViewModel.AllDocTypes[2].ToString();
                TabItem4_Notice.Header = ViewModel.AllDocTypes[3].ToString();

                TabItem5_Notice.Visibility = Visibility.Collapsed;
           
            }
            else if (i == 5)
            {
                TabItem1_Notice.Header = ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = ViewModel.AllDocTypes[2].ToString();
                TabItem4_Notice.Header = ViewModel.AllDocTypes[3].ToString();
                TabItem5_Notice.Header = ViewModel.AllDocTypes[4].ToString();
            }

        }
    }
}