using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

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

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

using DevExpress.Xpf.Grid;

namespace BeWo.View.Detail
{
    public partial class OrganisationView
    {
        private OrganisationVM _ViewModel;

        private GridControl grid_GroupBoxPersonGrid;

        public OrganisationView(OrganisationVM pOrganisationVM)
        {
            InitializeComponent();
            ViewModel = pOrganisationVM;

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

            tabitem_costbearer.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_AllowEditCostBearer) ? Visibility.Visible : Visibility.Collapsed;

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

        public event EventHandler<EventArgs<OrganisationVM>> OrganisationSavedOrUpdated;

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

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

        internal OrganisationVM ViewModel
        {
            get
            {
                return _ViewModel;
            }

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

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

        protected override void Save()
        {
            var lDC = ViewModel.CommitToDataContract();
            if (ViewModel.IsNew)
            {
                IsDoneWithInsertOrUpdate = false;
                ServiceFacade.DoCustomerServiceAsync(s => s.InsertNewOrganisation(lDC), ReloadViewModel);
            }
            else
            {
                IsDoneWithInsertOrUpdate = false;
                ServiceFacade.DoCustomerServiceAsync(s => s.UpdateOrganisation(lDC), ReloadViewModel);
            }

            Cache.GetInstance().ClearSupportConceptTree();
            BeWoApp.MainControl.ResetView(UIContext.Organisation);
        }

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

                            ViewModel = cb;

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

            IsDoneWithInsertOrUpdate = true;
        }

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

        private void bt_addQualificationRate_Click(object sender, RoutedEventArgs e)
        {
            var stand = ViewModel.CostRatePeriods.GetLatestRate(CostRatePeriodType.HourlyRate);
            if (stand != null)
            {
                ViewModel.CostRatePeriods.NewVM.CostRateValue = stand.CostRateValue;
            }

            ViewModel.CostRatePeriods.NewVM.ValueListEntry = (ValueListEntryDC) cb_qualifications.SelectedItem;
            ViewModel.CostRatePeriods.NewVM.CostRateType = CostRatePeriodType.HourlyRate;
            ViewModel.CostRatePeriods.AddNewVMToList();
        }

        private void button_deleteCostRatePeriodGroup_Click(object sender, RoutedEventArgs e)
        {
            var valueListEntry = (sender as Button).Tag as ValueListEntryDC;
            ViewModel.CostRatePeriods.VMList.RemoveRange(i => i.ValueListEntry != null && i.ValueListEntry.ValueListEntryOid.Equals(valueListEntry.ValueListEntryOid));
        }

        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.Organisation, ViewModel.DataContract.OrganisationOid.Value);
            }
        }

        private void TabItemsPersons_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_GroupBoxPersonGrid == null)
            {
                grid_GroupBoxPersonGrid    = gridroot.Resources["datagrid_PersonRelation"] as GridControl;
                GroupBoxPersonGrid.Content = grid_GroupBoxPersonGrid;
            }
        }

        private void TableView_OnRowDoubleClick(object sender, RowDoubleClickEventArgs e)
        {
            var grid = (GridControl) gridroot.Resources["datagrid_PersonRelation"];
            var selectedPerson = (grid.GetRow(e.HitInfo.RowHandle) as OrganisationPersonRelationVM).Person;

            if (selectedPerson == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.PersonView_View))
                return;

            VMFactory.CreatePersonVMAsync(selectedPerson.PersonOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<PersonVM, PersonDC, OrganisationView>(cb, this, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews(selectedPerson)), personSavedOrUpdated: (s, args) => this.Dispatch(delegate { }))));
        }

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

        private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            BeWoUtils.OpenMailClient(e.Uri.ToString());
        }
    }
}