using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;

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


namespace BeWo.View.Detail
{
    public class AmountFormatProvider : IFormatProvider, ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            // Convert argument to a string
            string result = arg.ToString();

            return result;
        }

        public object GetFormat(Type formatType)
        {
            // if (formatType == typeof(ICustomFormatter))
            return this;

            // else
            // return null;
        }
    }

    /// <summary>
    /// Interaktionslogik für AccountingTransactionEditView.xaml
    /// </summary>
    public partial class AccountingTransactionEditView : BeWoView
    {
        private AccountingBookingVM _BookingViewModel;

        private List<FlatSupportConceptTreeNodeDC> _FlatSupportConceptItems;

        private ValueListEntryDC _OldCategory;

        private AccountingTransactionVM _OriginalVM;

        private bool mHideCustomers;

        public AccountingTransactionEditView()
        {
            this.InitializeComponent();
        }

        public override bool CanDelete
        {
            get
            {
                return false;
            }
 // datagrid_grid.SelectedItem != null; }
        }

        public override bool IsDirty
        {
            get
            {
                return this.ViewModel.SelectedVM != null ? this.ViewModel.SelectedVM.IsDirty : false;
            }
        }

        public override string SaveObjectName
        {
            get
            {
                return "diese Buchung";
            }
        }

        public override string Title
        {
            get
            {
                return "Finanzbuchung bearbeiten";
            }
        }

        private AccountingBookingVM ViewModel
        {
            get
            {
                return this._BookingViewModel;
            }

            set
            {
                this._BookingViewModel = value;

            }
        }

        public void InitView(AccountingBookingVM pBookingViewModel, AccountingTransactionVM pATViewModel, List<FlatSupportConceptTreeNodeDC> flatSupportConceptItems, bool hideCustomerCombo)
        {
            this.InitializeComponent();

            
            this.combobox_categories.ItemsSource = pBookingViewModel.Categories;

            this.mHideCustomers = hideCustomerCombo;
            this._OriginalVM = pATViewModel;
            AccountingTransactionVM clone = pATViewModel.Clone();
            this.DataContext = clone;
            this._OldCategory = clone.Category;

            this._FlatSupportConceptItems = new List<FlatSupportConceptTreeNodeDC>();
            foreach (FlatSupportConceptTreeNodeDC node in flatSupportConceptItems)
            {
                if (node.SupportConceptTreeNodeDC != null && node.SupportConceptTreeNodeDC.Customer != null)
                {
                    FlatSupportConceptTreeNodeDC flatNode = new FlatSupportConceptTreeNodeDC();
                    flatNode.SupportConceptTreeNodeDC = node.SupportConceptTreeNodeDC;

                    this._FlatSupportConceptItems.Add(flatNode);
                }
                
            }

            pBookingViewModel.SelectedVM = clone;
            this.ViewModel = pBookingViewModel;

            // this.customerComboBox.ItemsSource = _FlatSupportConceptItems;
            if (!hideCustomerCombo)
            {
                this.supportConceptSelectionControl.Loaded += (s, e) => { this.SetSelectedCustomerNode(); };
            }
            else
            {
                this.supportConceptSelectionControl.Visibility = Visibility.Collapsed;
                this.customerComboColumn.Width = new GridLength(0);
            }

            this.Focus();
            this.textbox_Notice.Focus();

            this.Loaded += this.AccountingTransactionEditView_Loaded;
        }

        public bool IsCustomerChangeAllowed()
        {
            FlatSupportConceptTreeNodeDC selectedNode = this.ViewModel.SelectedVM.SupportConceptTreeNode;

            bool lAllowed = true;

            if (this._OriginalVM.CostBearerRel != null && selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC != null && this._OriginalVM.CostBearerRel.CostBearer2SupportConceptOid != selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid)
            {
                if (MessageBox.Show("Möchten Sie diese Buchung wirklich umbuchen?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                {
                    lAllowed = false;
                }
            }

            return lAllowed;
        }

        public bool IsValid()
        {
            FlatSupportConceptTreeNodeDC selectedNode = this.ViewModel.SelectedVM.SupportConceptTreeNode;

            bool lValid = true;

            if (!this.mHideCustomers && selectedNode == null)
            {
                lValid = false;
            }

            return ValidationTrigger.Validate(this.rootGrid) && lValid;
        }

        internal override bool DoSaveCheck()
        {
            if (this.IsDirty)
            {
                MessageBoxResult lResult = this.ShowSaveQuestion();
                if (lResult == MessageBoxResult.Cancel)
                {
                    this.Focus();
                    return false;
                }

                if (lResult == MessageBoxResult.Yes)
                {
                    if (!this.IsCustomerChangeAllowed())
                    {
                        return false;
                    }

                    this.SaveData();
                }
            }

            return true;
        }

        protected override void Save()
        {
            if (this.IsDirty)
            {
                this.ViewModel.SelectedVM.CopyTo(this._OriginalVM);
                FlatSupportConceptTreeNodeDC selectedNode = this.ViewModel.SelectedVM.SupportConceptTreeNode;

                if (!this.mHideCustomers)
                {
                    this._OriginalVM.SupportConceptTreeNode = selectedNode;
                }

                // this._OriginalVM.RoundedDuration = 
                // this._OriginalVM.ChoosenNode = 
                var lDC = this._OriginalVM.CommitToDataContract();
                List<AccountingTransactionDC> list = new List<AccountingTransactionDC>();
                list.Add(lDC);

                ServiceFacade.DoOperationsServiceAsync(s => s.UpdateAccountingTransactions(list), this.IncreaseVersion);
            }
        }

        private void AccountingTransactionEditView_Loaded(object sender, RoutedEventArgs e)
        {
            this.ViewModel.SelectedVM.Category = this._OldCategory;
            this.ViewModel.SelectedVM.SetDirty(false);
        }


        private void IncreaseVersion()
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { this._OriginalVM.DataContract.AccountingTransactionVersion++; });
        }

        private void SetSelectedCustomerNode()
        {
            FlatSupportConceptTreeNodeDC choosenNode = null;
            foreach (FlatSupportConceptTreeNodeDC node in this._FlatSupportConceptItems)
            {
                if (this._OriginalVM.CostBearerRel.Equals(node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC))
                {
                    choosenNode = node;
                }
            }
			foreach (FlatSupportConceptTreeNodeDC node in this._FlatSupportConceptItems)
			{
				if (node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid.HasValue && node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid.Value == 150)
				{
					int test = 0;
				}
			}
            this.supportConceptSelectionControl.SelectedItem = choosenNode;


            this.ViewModel.SelectedVM.SupportConceptTreeNode = choosenNode;
        }

        private void supportConceptSelectionControl_ItemSelected(object sender, EventArgs<FlatSupportConceptTreeNodeDC> e)
        {
            FlatSupportConceptTreeNodeDC selectedNode = e.Data;
            if (selectedNode != null && this.ViewModel != null)
            {
                this.ViewModel.SelectedVM.SupportConceptTreeNode = selectedNode;
            }
        }


    }
}