using System;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;

using BeWo.Controls;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

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

namespace BeWo.View.Detail.Accounting
{
    public partial class GeneralInvoiceView : BeWoView
    {
        private readonly GeneralInvoiceItemEditView _EditView;

        private CompactCustomerDC _SelectedCustomer;

        private CompactOrganisationDC _SelectedOrganisation;

        private CompactPersonDC _SelectedPerson;

        private InvoiceBaseListVM _Viewmodel;

        public GeneralInvoiceView()
        {
            InitializeComponent();
            _EditView = new GeneralInvoiceItemEditView();
            _EditView.EditingFinished += (s, e) =>
            {
                MainControl.CloseCurrentPopUp();
                ReloadViewModel();
            };
        }

        public CompactOrganisationDC SelectedOrganisation
        {
            get { return _SelectedOrganisation; }
            set { _SelectedOrganisation = value; }
        }

        internal InvoiceBaseListVM ViewModel
        {
            get { return _Viewmodel; }

            set
            {
                DataContext = value;
                _Viewmodel = value;
            }
        }

        private void CustomerSearchView_ItemSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            popup_Recipient.IsOpen = false;
            _SelectedOrganisation = null;
            _SelectedPerson = null;
            _SelectedCustomer = e.Data;
            ReloadViewModel();
            popupedit_Recipient.Text = _SelectedCustomer.FullName;
        }

        private void OrganisationSearchView_ItemSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {
            popup_Recipient.IsOpen = false;
            _SelectedOrganisation = e.Data;
            _SelectedPerson = null;
            _SelectedCustomer = null;
            ReloadViewModel();
            popupedit_Recipient.Text = _SelectedOrganisation.Name;
        }

        private void PersonSearchView_ItemSelected(object sender, EventArgs<CompactPersonDC> e)
        {
            popup_Recipient.IsOpen = false;
            _SelectedOrganisation = null;
            _SelectedPerson = e.Data;
            _SelectedCustomer = null;
            ReloadViewModel();
            popupedit_Recipient.Text = _SelectedPerson.FullName;
        }

        private void ReloadViewModel()
        {
            VMFactory.CreateGeneralInvoiceBaselListVMAsync(_SelectedCustomer, _SelectedOrganisation, _SelectedPerson, r => this.Dispatch(delegate { ViewModel = r; }));
        }

        private void StartEditNewVM()
        {
            this.Dispatch(
                delegate
                {
                    _EditView.ViewModel = ViewModel.NewVM;
                    MainControl.ShowControlAsModalPopUp(_EditView);
                });
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Sind Sie sicher, dass Sie den gewählten Eintrag löschen möchten?", "Rechnung löschen", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                var vm = BeWoWpfUtils.GetTag<InvoiceBaseVM>(sender);
                ViewModel.VMList.Remove(vm);
                ServiceFacade.DoAccountingServiceAsync(s => s.DeactivateInvoiceBases(new[] {vm.DataContract}.ToList()));
            }
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            _EditView.ViewModel = BeWoWpfUtils.GetTag<InvoiceBaseVM>(sender);
            MainControl.ShowControlAsModalPopUp(_EditView);
        }

        private void button_add_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.NewVM.DataContract.Type                  = InvoiceType.General;
            ViewModel.NewVM.CreatorFirstName                   = BeWoApp.LoggedOnEmployee.FirstName;
            ViewModel.NewVM.CreatorLastName                    = BeWoApp.LoggedOnEmployee.LastName;
            ViewModel.NewVM.SenderFirstName                    = BeWoApp.LoggedOnEmployee.FirstName;
            ViewModel.NewVM.SenderLastName                     = BeWoApp.LoggedOnEmployee.LastName;
            ViewModel.NewVM.SenderOrganisation                 = BeWoApp.Mandator.Name;
            ViewModel.NewVM.InvoiceDate                        = DateTime.Now.Date;
            ViewModel.NewVM.AccountingPeriodStart              = DateTime.Now.Date.AddDays(-DateTime.Now.Day + 1).AddMonths(-1);
            ViewModel.NewVM.AccountingPeriodEnd                = DateTime.Now.Date.AddDays(-DateTime.Now.Day);
            ViewModel.NewVM.InvoiceItems.NewVM.ItemPeriodStart = ViewModel.NewVM.AccountingPeriodStart;
            ViewModel.NewVM.InvoiceItems.NewVM.ItemPeriodEnd   = ViewModel.NewVM.AccountingPeriodEnd;
            ViewModel.NewVM.InvoiceItems.AddNewVMToList();

            foreach (ContactDC iContactDC in BeWoApp.LoggedOnEmployee.ContactInformations)
            {
                if (iContactDC.ContactType == ContactType.business_Fax)
                {
                    ViewModel.NewVM.SenderFax = iContactDC.ContactValue;
                }

                if (iContactDC.ContactType == ContactType.business_Phone)
                {
                    ViewModel.NewVM.SenderPhone = iContactDC.ContactValue;
                }
            }

            if (_SelectedCustomer != null)
            {
                ServiceFacade.DoCustomerServiceAsync(
                    s => s.LoadCustomer(_SelectedCustomer.CustomerOid),
                    r =>
                    {
                        ViewModel.NewVM.RecipientCustomerOid     = _SelectedCustomer.CustomerOid;
                        ViewModel.NewVM.RecipientPersonFirstName = r.FirstName;
                        ViewModel.NewVM.RecipientPersonLastName  = r.LastName;
                        ViewModel.NewVM.RecipientStreet          = r.InvoiceAddressStreet ?? r.Street;
                        ViewModel.NewVM.RecipientTown            = r.InvoiceAddressTown ?? r.Town;
                        ViewModel.NewVM.RecipientPostCode        = r.InvoiceAddressPostalCode ?? r.PostalCode;
                        ViewModel.NewVM.CustomerReferenceNumber  = r.ReferenceNumber;
                        StartEditNewVM();
                    });
            }
            else if (_SelectedPerson != null)
            {
                ServiceFacade.DoCustomerServiceAsync(
                    s => s.LoadPerson(_SelectedPerson.PersonOid),
                    r =>
                    {
                        ViewModel.NewVM.RecipientPersonOid       = _SelectedPerson.PersonOid;
                        ViewModel.NewVM.RecipientPersonFirstName = r.FirstName;
                        ViewModel.NewVM.RecipientPersonLastName  = r.LastName;
                        ViewModel.NewVM.RecipientStreet          = r.InvoiceAddressStreet;
                        ViewModel.NewVM.RecipientTown            = r.InvoiceAddressTown;
                        ViewModel.NewVM.RecipientPostCode        = r.InvoiceAddressPostalCode;
                        StartEditNewVM();
                    });
            }
            else if (_SelectedOrganisation != null)
            {
                ServiceFacade.DoCustomerServiceAsync(
                    s => s.LoadOrganisation(_SelectedOrganisation.OrganisationOid),
                    r =>
                    {
                        ViewModel.NewVM.RecipientOrganisationOid = _SelectedOrganisation.OrganisationOid;
                        ViewModel.NewVM.RecipientOrganisation    = r.Name;
                        ViewModel.NewVM.RecipientStreet          = r.InvoiceAddressStreet;
                        ViewModel.NewVM.RecipientTown            = r.InvoiceAddressTown;

                        if (r.ContactInformations.FirstOrDefault(f => f.ContactType == ContactType.business_POBox) != null)
                        {
                            ViewModel.NewVM.RecipientPostBox = r.ContactInformations.First(f => f.ContactType == ContactType.business_POBox).ContactValue;
                        }

                        ViewModel.NewVM.RecipientPostCode = r.InvoiceAddressPostalCode;
                        StartEditNewVM();
                    });
            }
        }

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


        private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            BeWoUtils.NavigateToReportUri((sender as Hyperlink).NavigateUri.ToString(), "Druckvorschau");
        }

        private void Popupedit_Recipient_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit) sender, e) || _SelectedOrganisation == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_Edit))
                return;

            VMFactory.CreateOrganisationVMAsync(_SelectedOrganisation.OrganisationOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, GeneralInvoiceView>(cb, this, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews(_SelectedOrganisation)), _OrganisationModalPopUp_OrganisationSavedOrUpdated)));
        }

        private void _OrganisationModalPopUp_OrganisationSavedOrUpdated(object sender, EventArgs<OrganisationVM> e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadOrganisationCompact(e.Data.DataContract.OrganisationOid.Value),
                p => this.Dispatch(
                    delegate
                    {
                        _SelectedOrganisation = p;
                        popupedit_Recipient.Focus();
                        MainControl.CloseCurrentPopUp();
                    }));
        }
    }
}