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

using BeWo.Controls;
using BeWo.Core;
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 PersonView
    {
        internal OrganisationView _OrganisationModalPopUp;

        private PersonVM _ViewModel;

        private GridControl grid_relations;

        public PersonView(PersonVM pPersonVM)
        {
            InitializeComponent();
            ViewModel = pPersonVM;

            if (pPersonVM.VarFields == null || pPersonVM.VarFields.VMList.Count == 0)
            {
                tabitem_varFields.Visibility = Visibility.Collapsed;
            }

            comboBox_Title.ItemsSource = pPersonVM.Titles;
            comboBox_Function.ItemsSource = pPersonVM.Functions;

            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Person_AllowArchiving))
            {
                lblArchiviert.Visibility = Visibility.Hidden;
                chkArchiviert.Visibility = Visibility.Hidden;
            }
			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.DocumentsAllowViewAll) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.DokumentePersonen))
			{
				tabitem_documents.Visibility = Visibility.Collapsed;
			}
        }

        public event EventHandler<EventArgs<PersonVM>> PersonSavedOrUpdated;

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

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

        public PersonVM ViewModel
        {
            get
            {
                return _ViewModel;
            }

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

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

        public override void ModalPopUpCloseInvoked()
        {
            MainControl.CloseCurrentPopUp();
            _OrganisationModalPopUp = null;
        }

        public override void ModalPopUpSaveInvoked()
        {
            _OrganisationModalPopUp.SaveData();
        }

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

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

            if (ViewModel.IsNew)
            {
                IsDoneWithInsertOrUpdate = false;
                ServiceFacade.DoCustomerServiceAsync(s => s.InsertNewPerson(lDC), ReloadViewModel);
            }
            else
            {
                ServiceFacade.DoCustomerServiceAsync(s => s.UpdatePerson(lDC), ReloadViewModel);
                IsDoneWithInsertOrUpdate = false;
            }

            BeWoApp.MainControl.ResetView(UIContext.Person);
        }

        private void OrganisationSearchView_OrganisationSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {

			popup_organisation.IsOpen = false;
			organisationSearchView.ItemSelected -= OrganisationSearchView_OrganisationSelected;
			ViewModel.OrganisationRelations.NewVM.Organisation = e.Data;
			popupedit_organisation.Focus();

            //VMFactory.CreatePersonOrganisationRelationVMAsync(e.Data, cb => this.Dispatch(delegate { this.ViewModel.NewOrganisationRelation = cb; }));
            //this.popup_organisation.IsOpen = false;
			BeWoUtils.UpdateAllViews(e.Data);
        }

        private void ReloadViewModel(long pOid)
        {
            VMFactory.CreatePersonVMAsync(
                pOid, 
                cb => this.Dispatch(
                    delegate
                        {
                            if (PersonSavedOrUpdated != null)
                            {
                                PersonSavedOrUpdated(this, new EventArgs<PersonVM>(cb));
                            }

                            ViewModel = cb;

                            if (ModalEditViewUpdateCallback != null)
                            {
                                ModalEditViewUpdateCallback();
                            }
                        }));

            IsDoneWithInsertOrUpdate = true;
        }

        public void ReloadViewModel()
        {
            ReloadViewModel(ViewModel.DataContract.PersonOid.Value);
        }

        private void TabItemOrganisations_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_relations == null)
            {
                grid_relations = rootGrid.Resources["grid_Relations"] as GridControl;
                GroupBoxOrganisation.Content = grid_relations;
            }
        }

        private void _OrganisationModalPopUp_OrganisationSavedOrUpdated(object sender, EventArgs<OrganisationVM> e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadOrganisationCompact(e.Data.DataContract.OrganisationOid.Value),
                o => this.Dispatch(

                        delegate
                            {
                                ViewModel.OrganisationRelations.NewVM.Organisation = o;
                                popupedit_organisation.Focus();
								BeWoUtils.UpdateAllViews(o);
                                MainControl.CloseCurrentPopUp();
                                _OrganisationModalPopUp = null;
                            }));
        }

        private void button_addOrganisationRelation_Click(object sender, RoutedEventArgs e)
        {
			if (ValidationTrigger.Validate(groupbox_newOrganisation))
			{
				ViewModel.OrganisationRelations.AddNewVMToList();
			}

			//if (this.ViewModel.NewOrganisationRelation == null || !this.ViewModel.NewOrganisationRelation.DataContract.OrganisationOid.HasValue)
			//{
			//    MessageBox.Show("Bitte wählen Sie eine Organisation aus.", "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Information);
			//}
			//else
			//{
			//    this.ViewModel.OrganisationRelations.Add(this.ViewModel.NewOrganisationRelation);
			//    this.ViewModel.NewOrganisationRelation = null;
			//}
        }

        private void button_removeOrganisationRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.OrganisationRelations.VMList.Remove(grid_relations.GetCurrentValue<PersonOrganisationRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_relations);
        }

        private void popupedit_organisation_NewClick(object sender, RoutedEventArgs e)
        {
            VMFactory.CreateOrganisationVMAsync(
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, PersonView>(cb, this,
                    () => this.Dispatch(delegate { }),
                    _OrganisationModalPopUp_OrganisationSavedOrUpdated)));
        }

        private void popupedit_organisation_PopUpClick(object sender, RoutedEventArgs e)
        {
			organisationSearchView.ItemSelected += OrganisationSearchView_OrganisationSelected;
            popup_organisation.IsOpen = true;
        }

        private void tabitem_documents_Selected(object sender, RoutedEventArgs e)
        {
            if (ViewModel.IsNew)
            {
                MessageBox.Show("Bevor zu einem Datensatz Dokumente hinterlegt werden können, muss dieser gespeichert werden.", "Erst speichern bitte", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (tabitem_documents.Content == null)
            {
                tabitem_documents.Content = new BeWoFileView(TableID.Person, ViewModel.DataContract.PersonOid.Value);
            }
        }
		
		private void Popupedit_organisation_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) ||
				!BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_Edit) ||
				ViewModel.OrganisationRelations.NewVM.Organisation == null)
			{
			    return;
			}

			VMFactory.CreateOrganisationVMAsync(ViewModel.OrganisationRelations.NewVM.Organisation.OrganisationOid,
					cb => this.Dispatch(
						() => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, PersonView>(cb, this,
						() =>
						this.Dispatch(
							delegate
							{
								var updatedOrganisation = new CompactOrganisationDC();

								ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact(ViewModel.OrganisationRelations.NewVM.Organisation.OrganisationOid));
								BeWoUtils.UpdateAllViews(updatedOrganisation);
							}),

						_OrganisationModalPopUp_OrganisationSavedOrUpdated)));
		}

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

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_View) || selectedVM == null)
			{
			    return;
			}

			VMFactory.CreateOrganisationVMAsync(selectedVM.Organisation.OrganisationOid,
					cb => this.Dispatch(
						() => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, PersonView>(cb, this,
						() => this.Dispatch(
							delegate
							{
								var updatedOrganisation = new CompactOrganisationDC();

								ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact(selectedVM.Organisation.OrganisationOid));
								BeWoUtils.UpdateAllViews(updatedOrganisation);
							}), (s, args) => this.Dispatch(delegate { })
						)));
		}

        private void EMailButton_OnClick(object sender, RoutedEventArgs e)
        {
            BeWoUtils.OpenMailClient(ViewModel.PrivateEMail);
        }
    }
}