using System;
using System.Linq;
using System.Windows;
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 EquityInvoiceView : BeWoView
    {
        private readonly EquityInvoiceItemEditView _EditView;

        private CompactSupportConceptDC _SelectedSupportConcept;

        private InvoiceBaseListVM _Viewmodel;

        public CompactSupportConceptDC SelectedSupportConcept
        {
            get { return _SelectedSupportConcept; }
            set { _SelectedSupportConcept = value; }
        }

        public EquityInvoiceView()
        {
            this.InitializeComponent();

            this._EditView = new EquityInvoiceItemEditView();
            this._EditView.EditingFinished += (s, e) =>
                {
                    // hyperlinkPrint.
                    this.MainControl.CloseCurrentPopUp();
                    this.ReloadViewModel();
                };
        }

        internal InvoiceBaseListVM ViewModel
        {
            get
            {
                return this._Viewmodel;
            }

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

        internal void ReloadViewModel()
        {
            VMFactory.CreateEquityInvoiceBaselListVMAsync(this._SelectedSupportConcept.SupportConceptOid, r => this.Dispatch(delegate { this.ViewModel = r; }));
        }

        private void SupportConceptSearchView_ItemSelected(object sender, EventArgs<CompactSupportConceptDC> e)
        {
            this.popup_costBearer.IsOpen = false;
            this.popupedit_CostBeaerer.Text = e.Data.DetailDescription;
            this._SelectedSupportConcept = e.Data;
            this.ReloadViewModel();
        }

        private void bt_add_Click(object sender, RoutedEventArgs e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadCustomer(this._SelectedSupportConcept.Customer.CustomerOid), 
                r =>
                    {
                        this.ViewModel.NewVM.DataContract.Type = InvoiceType.CustomerEquity;

                        this.ViewModel.NewVM.SupportConceptOid = this._SelectedSupportConcept.SupportConceptOid;
                        this.ViewModel.NewVM.RecipientCustomerOid = this._SelectedSupportConcept.Customer.CustomerOid;
                        this.ViewModel.NewVM.RecipientPersonFirstName = r.FirstName;
                        this.ViewModel.NewVM.RecipientPersonLastName = r.LastName;
                        this.ViewModel.NewVM.RecipientStreet = r.InvoiceAddressStreet ?? r.Street;
                        this.ViewModel.NewVM.RecipientTown = r.InvoiceAddressTown ?? r.Town;
                        this.ViewModel.NewVM.RecipientPostCode = r.InvoiceAddressPostalCode ?? r.PostalCode;
                        this.ViewModel.NewVM.CustomerReferenceNumber = r.ReferenceNumber;
                        this.ViewModel.NewVM.CreatorFirstName = BeWoApp.LoggedOnEmployee.FirstName;
                        this.ViewModel.NewVM.CreatorLastName = BeWoApp.LoggedOnEmployee.LastName;
                        this.ViewModel.NewVM.SenderFirstName = BeWoApp.LoggedOnEmployee.FirstName;
                        this.ViewModel.NewVM.SenderLastName = BeWoApp.LoggedOnEmployee.LastName;
                        this.ViewModel.NewVM.SenderOrganisation = BeWoApp.Mandator.Name;

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

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

                        this.ViewModel.NewVM.InvoiceDate = DateTime.Now.Date;
                        this.ViewModel.NewVM.AccountingPeriodStart = DateTime.Now.Date.AddDays(-DateTime.Now.Day + 1).AddMonths(-1);
                        this.ViewModel.NewVM.AccountingPeriodEnd = DateTime.Now.Date.AddDays(-DateTime.Now.Day);

                        this.ViewModel.NewVM.InvoiceItems.NewVM.ItemPeriodStart = this.ViewModel.NewVM.AccountingPeriodStart;
                        this.ViewModel.NewVM.InvoiceItems.NewVM.ItemPeriodEnd = this.ViewModel.NewVM.AccountingPeriodEnd;
                        this.ViewModel.NewVM.InvoiceItems.NewVM.UnitCount = 1;
                        this.ViewModel.NewVM.InvoiceItems.NewVM.ItemDescription = "monatl. Eigenanteil";
                        this.ViewModel.NewVM.InvoiceItems.NewVM.AmountPerUnit = r.EquityContribution;
                        this.ViewModel.NewVM.InvoiceItems.NewVM.AmountTotal = r.EquityContribution;
                        this.ViewModel.NewVM.InvoiceItems.AddNewVMToList();

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

        private void bt_delete_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);
                this.ViewModel.VMList.Remove(vm);
                ServiceFacade.DoAccountingServiceAsync(s => s.DeactivateInvoiceBases(new[] { vm.DataContract }.ToList()));
            }
        }

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

        private void popupedit_CostBeaerer_PopUpClick(object sender, RoutedEventArgs ev)
        {
            this.popup_costBearer.IsOpen = true;
        }

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

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

            VMFactory.CreateSupportConceptVMAsync(_SelectedSupportConcept.SupportConceptOid,
                cb => this.Dispatch(
                            () => BeWoUtils.OpenModalViewWindow<SupportConceptVM, SupportConceptDC, EquityInvoiceView>(cb, this, 
                            () => this.Dispatch(delegate { BeWoUtils.UpdateAllViews(_SelectedSupportConcept); }))));
        }
    }
}