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

using BeWo.ServiceProxy;
using BeWo.ViewModel;

namespace BeWo.View.Detail.Accounting
{
    public partial class SettlementInvoiceItemEditView : BeWoView
    {
        private SettlementVM _Viewmodel;

        public SettlementInvoiceItemEditView()
        {
            this.InitializeComponent();

            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => this.FireEditingFinished()));
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, (s, e) => this.SaveData()));
        }

        public event EventHandler<EventArgs> EditingFinished;

        public SettlementVM ViewModel
        {
            get
            {
                return this._Viewmodel;
            }

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

        protected override void Save()
        {
            var dc = new[] { this.ViewModel.CommitToDataContract() }.ToList();

            if (this.ViewModel.IsNew)
            {
                ServiceFacade.DoAccountingServiceAsync(
                    s => s.InsertNewSettlementInvoice(dc), 
                    r =>
                        {
                            if (r.Count > 0)
                            {
                                this.ViewModel.DataContract.SettlementIvoiceOid = r[0];
                            }

                            this.FireEditingFinished();
                        });
            }
            else
            {
                ServiceFacade.DoAccountingServiceAsync(s => s.UpdateSettlementInvoice(dc), this.FireEditingFinished);
            }
        }

        private void FireEditingFinished()
        {
            if (this.EditingFinished != null)
            {
                this.EditingFinished(this, new EventArgs());
            }
        }
    }
}