using System.ServiceModel;
using System.Windows;
using System.Windows.Input;

using BeWo.Controls;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;

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

using DevExpress.Xpf.Grid;


namespace BeWo.View.Detail
{
	public partial class WohnheimView : BeWoView
	{
		private WohnheimVM _ViewModel;

		private bool initTabIndex;

		public WohnheimView(WohnheimVM pWohnheimDC)
		{
			InitializeComponent();
			ViewModel = pWohnheimDC;

			// HACK: Force the devexpress grid to end editing when the mouse is over savebutton
			// by setting the focus to another element. 
			MouseMove += (s, e) =>
			{
				if ((grid_EmployeeRelation == null || !grid_EmployeeRelation.IsVisible) &&
                     (grid_CustomerRelation == null || !grid_CustomerRelation.IsVisible))
				{
					return;
				}

                	var p = e.GetPosition(btnSave);

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

            //ich glaub es ist alles gesagt
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Wohnheim_AllowArchiving))
            {
                lblArchiviert.Visibility = Visibility.Hidden;
                chkArchiviert.Visibility = Visibility.Hidden;
            }
			
		}

        private void UserControl_GotFocus(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource.Equals(this))
            {
                textbox_first.Focus();
            }
        }

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

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

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

		internal WohnheimVM ViewModel
		{
			get { return _ViewModel; }

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

		protected override UserRightType[] GetSaveDemands()
		{
		    return ViewModel.IsNew ? new[] {UserRightType.CreateAll, UserRightType.WohnheimView_Create} : new[] {UserRightType.EditAll, UserRightType.WohnheimView_Edit};
		}

	    protected override void Save()
		{
			var lDataContract = ViewModel.CommitToDataContract();


            //Abfrage if Name is null or empty -> Message Bitte den Namen eingeben
            if(textbox_first.Text.Equals("")){
                textbox_first.Focus(); 
                MessageBox.Show("Bitte dem Wohnheim einen Namen geben.");
            }
            else{
            //sonst 
			    try
			    {
				    if (ViewModel.IsNew)
				    {
					    IsDoneWithInsertOrUpdate = false;
                        ServiceFacade.DoCustomerServiceAsync(s => s.InsertNewWohnheim(lDataContract), ReloadViewModel);
				    }
				    else
				    {   
					    IsDoneWithInsertOrUpdate = false;
                        ServiceFacade.DoCustomerServiceAsync(s => s.UpdateWohnheim(lDataContract), ReloadViewModel);
				    }

				    Cache.GetInstance().ClearEmployees();
				    BeWoApp.MainControl.ResetView(UIContext.Wohnheim);
			    }
			    catch (FaultException<BeWoFault>)
			    {
				    MessageBox.Show(
					    "Dieser Datensatz wurde in der Zwischenzeit von einem anderen Benutzer geändert. Klicken Sie Ok um den Datansatz erneut zu laden. Ihre Änderungen gehen dabei leider verloren.");
				    ReloadViewModel(lDataContract.WohnheimOid.Value);
			    } 
            }
		}

		private void ReloadViewModel(long pOid)
		{
			VMFactory.CreateWohnheimVMAsync(pOid, cb => this.Dispatch(delegate { ViewModel = cb; }));
			
			IsDoneWithInsertOrUpdate = true;
		}

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

        private void button_addKlientRelation_Klick(object sender, RoutedEventArgs e)
        {
            popup_newKlientRel.IsOpen = true;

        }

        private void button_addEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newEmployeeRel))
            {
                popup_newEmployeeRel.IsOpen = false;
                ViewModel.WohnheimEmployeeRelations.AddNewVMToList();
            }
        }

        private void button_cancelEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {
            popup_newEmployeeRel.IsOpen = false;
        }

        private void Employeesearchview_EnvironmentEmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popup_employee.IsOpen = false;
            employeesearchview.ItemSelected -= Employeesearchview_EnvironmentEmployeeSelected;
            ViewModel.WohnheimEmployeeRelations.NewVM.Employee = e.Data;
            popup_employee.Focus();
        }

        private void popupedit_EmployeeRelations_PopUpClick(object sender, RoutedEventArgs e)
        {
            employeesearchview.ItemSelected += Employeesearchview_EnvironmentEmployeeSelected;
            popup_employee.IsOpen = true;
        }

        private void Popupedit_EmployeeRelations_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            CreateModalViewWindow(ViewModel.WohnheimEmployeeRelations.NewVM.Employee);
        }

        public void button_removeEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.WohnheimEmployeeRelations.VMList.Remove(grid_EmployeeRelation.GetCurrentValue<WohnheimEmployeeRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_EmployeeRelation);
        }

        private void button_addKlientRelation_Click(object sender, RoutedEventArgs e)
        {
            popup_newKlientRel.IsOpen = false;
            ViewModel.WohnheimCustomerRelations.AddNewVMToList();
        }

        private void button_cancelKlientRelation_Click(object sender, RoutedEventArgs e)
        {
            popup_newKlientRel.IsOpen = false;
        }

        private void Klientsearchview_EnvironmentKlientSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            popup_klient.IsOpen = false;
            klientsearchview.ItemSelected -= Klientsearchview_EnvironmentKlientSelected;
            ViewModel.WohnheimCustomerRelations.NewVM.Customer = e.Data;
            popup_klient.Focus();
        }

        private void popupedit_KlientRelations_PopUpClick(object sender, RoutedEventArgs e)
        {
            klientsearchview.ItemSelected += Klientsearchview_EnvironmentKlientSelected;
            popup_klient.IsOpen = true;
        }

        private void Popupedit_KlientRelations_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit) sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.WohnheimView_View))
            {
                return;
            }

            CreateModalViewWindow(ViewModel.WohnheimCustomerRelations.NewVM.Customer);
        }

        public void Button_RemoveCustomerRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.WohnheimCustomerRelations.VMList.Remove(grid_CustomerRelation.GetCurrentValue<WohnheimCustomerRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_CustomerRelation);
        }

        private void TableViewCustomer_OnRowDoubleClick(object sender, RowDoubleClickEventArgs e)
        {
            var tableView = (TableView)sender;
            var selectedVM = (WohnheimCustomerRelationVM)tableView.Grid.GetRow(e.HitInfo.RowHandle);

            if (selectedVM == null)
            {
                return;
            }

            CreateModalViewWindow((selectedVM).Customer);
        }

        private void TableViewEmployee_OnRowDoubleClick(object sender, RowDoubleClickEventArgs e)
        {
            var tableView = (TableView) sender;
            var selectedVM = (WohnheimEmployeeRelationVM) tableView.Grid.GetRow(e.HitInfo.RowHandle);

            if (selectedVM == null)
            {
                return;
            }

            CreateModalViewWindow((selectedVM).Employee);
        }

        private void CreateModalViewWindow<T>(T pDC) where T : IDataContract
        {
            var pDCType = pDC.GetType();

            if (pDCType == typeof(CompactEmployeeDC))
            {
               VMFactory.CreateEmployeeVMAsync((pDC as CompactEmployeeDC).EmployeeOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, WohnheimView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews((pDC as CompactEmployeeDC))))));
            }

            if (pDCType == typeof (CompactCustomerDC))
            {
                VMFactory.CreateCustomerVMAsync((pDC as CompactCustomerDC).CustomerOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, WohnheimView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews((pDC as CompactCustomerDC))))));
            }
        }
	}
}