using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

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

using DevExpress.Xpf.Grid;

namespace BeWo.View.Detail.Accounting
{
    public partial class ServiceInvoiceCreatePopUpView : BeWoView
    {
        private BindingList<ServiceInvoiceDC> _Dcs;

        private List<string> _InvoiceNumbers;

        public ServiceInvoiceCreatePopUpView()
        {
            this.InitializeComponent();

            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, 
                                                        (s, e) =>
                                                        {
                                                            this._Dcs.Clear();
                                                            this.Fire();
                                                        }));

            this.grid_newInvoices.View.Loaded += (s, e) => ((TableView)this.grid_newInvoices.View).BestFitColumns();
        }

        public event EventHandler<EventArgs<List<ServiceInvoiceDC>>> Closed;

        public List<ServiceInvoiceDC> ServiceInvoiceDcs
        {
            set
            {
                this._InvoiceNumbers = value.Select(i => i.InvoiceBase.InvoiceNumber).ToList();
                this._Dcs = new BindingList<ServiceInvoiceDC>(value);
                this.grid_newInvoices.ItemsSource = this._Dcs;
            }
        }

        private void Fire()
        {
            if (this.Closed != null)
            {
                for (int i = 0; i < this._Dcs.Count; i++)
                {
                    this._Dcs[i].InvoiceBase.InvoiceNumber = this._InvoiceNumbers[i];
                }

                this.Closed(this, new EventArgs<List<ServiceInvoiceDC>>(new List<ServiceInvoiceDC>(this._Dcs)));
            }
        }

        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            this._Dcs.Clear();
            this.Fire();
        }

        private void btn_create_Click(object sender, RoutedEventArgs e)
        {
            this.Fire();
        }

        private void btn_delete_Click(object sender, RoutedEventArgs e)
        {
            this._Dcs.Remove(this.grid_newInvoices.GetCurrentValue<ServiceInvoiceDC>());
        }
    }
}