using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BeWo.ServiceProxy;

namespace BeWo.View.Controls
{
    /// <summary>
    /// Interaktionslogik für CompactAdditionalServiceGroupControl.xaml
    /// </summary>
    public partial class CompactAdditionalServiceGroupControl : UserControl
    {
        private ObservableSortCollection<CompactCustomerDC> mSelectedCustomers;
        private AdditionalServiceGroupOfPeopleDC ASGroup;

        public CompactAdditionalServiceGroupControl()
        {
            InitializeComponent();
            UpdateListBox();
        }

        public virtual bool AutoGetAllAfterLoaded
        {
            get { return SearchView != null && SearchView.AutoGetAllAfterLoaded; }
            set { SearchView.AutoGetAllAfterLoaded = value; }
        }

        public Dictionary<long?, bool> Participations { get; set; }

        public List<CompactCustomerDC> CustomerList
        {
            get { return SearchView != null ? SearchView.Customers : null; }
            set
            {
                value.Sort((x, y) => (x.LastName + ", " + x.FirstName).CompareTo(y.LastName + ", " + y.FirstName));
                SearchView.Customers = value;
            }
        }

        public event EventHandler<EventArgs<CompactCustomerDC>> ItemSelected;

        public CompactCustomerDC SelectedItem
        {
            get
            {
                return listBoxCustomers != null
                           ? listBoxCustomers.SelectedItem as CompactCustomerDC
                           : null;
            }
        }

        public ObservableSortCollection<CompactCustomerDC> SelectedCustomers
        {
            get
            {
                if (mSelectedCustomers == null)
                {
                    mSelectedCustomers = new ObservableSortCollection<CompactCustomerDC>();
                    mSelectedCustomers.CollectionChanged += mSelectedCustomers_CollectionChanged;
                }

                return mSelectedCustomers;
            }
        }

        public void setGroupMembers(List<CompactCustomerDC> customers, AdditionalServiceGroupOfPeopleDC group)
        {
            if (SelectedCustomers == null) 
                return;

            ASGroup = group;

            var allCustomers = new List<CompactCustomerDC>();
            SelectedCustomers.Clear();

            ServiceFacade.DoCustomerServiceSync(s => allCustomers = s.GetAllActiveCustomersCompact(false, BeWoApp.LoggedOnEmployee.EmployeeOid));

            foreach (var item in customers)
            {
                SelectedCustomers.Add(item);
                allCustomers.Remove(item);
            }

            allCustomers.Sort((x, y) => (x.LastName + ", " + x.FirstName).CompareTo(y.LastName + ", " + y.FirstName));
            SearchView.Customers = allCustomers;
        }

        private void CustomerSearchView_ItemSelected(object sender, EventArgs<CompactCustomerDC> e)
        {   
            popupCustomers.IsOpen = false;

            if (SelectedCustomers == null || SelectedCustomers.Contains(e.Data)) 
                return;

            SelectedCustomers.Add(e.Data);
            listBoxCustomers.ScrollIntoView(e.Data);

            ASGroup.CustomerList.Add(e.Data);
            var a = new AdditionalServiceGroupOfPeopleDC();
            ServiceFacade.DoOperationsServiceSync(r => a = r.UpdateAdditionalServiceGroupOfPeople(ASGroup));

            var b = a.CustomerList;
            setGroupMembers(b, a);
        }

        private void UpdateListBox()
        {
            if (listBoxCustomers != null)
                listBoxCustomers.ItemsSource = SelectedCustomers;
        }
        
        private void btnAddCustomer_Click(object sender, RoutedEventArgs e)
        {
            popupCustomers.IsOpen = true;
        }

        private void btnRemoveCustomer_Click(object sender, RoutedEventArgs e)
        {   
            var dc = ((Button)sender).Tag as CompactCustomerDC;
            
            if (dc == null || MessageBox.Show(
                "Sind Sie sicher, dass Sie " + dc.FullName + " aus der Gruppe entfernen möchten?", "Löschen",
                MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) 
                return;

            ASGroup.CustomerList.Remove(dc);
            var a = new AdditionalServiceGroupOfPeopleDC();
            ServiceFacade.DoOperationsServiceSync(r => a = r.UpdateAdditionalServiceGroupOfPeople(ASGroup));

            var b = a.CustomerList;
            setGroupMembers(b, a);

            SelectedCustomers.Remove(dc);
            var tempListe = SearchView.Customers;

            if(!tempListe.Contains(dc)) 
                tempListe.Add(dc);

            tempListe.Sort((x, y) => (x.LastName + ", " + x.FirstName).CompareTo(y.LastName + ", " + y.FirstName));
            SearchView.Customers = tempListe;
        }

        private void listBoxCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CompactCustomerDC dc = null;
            if (e.AddedItems != null && e.AddedItems.Count > 0)
                dc = e.AddedItems[0] as CompactCustomerDC;

            if (ItemSelected != null)
                ItemSelected(this, new EventArgs<CompactCustomerDC>(dc));
        }

        private void mSelectedCustomers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {   
            if (SearchView == null || SearchView.Customers == null)
                return;
            
            var tempCustomers = SearchView.Customers;

            foreach (var item in mSelectedCustomers.ToList().Where(tempCustomers.Contains))
                tempCustomers.Remove(item);

            tempCustomers.Sort((x, y) => (x.LastName + ", " + x.FirstName).CompareTo(y.LastName + ", " + y.FirstName));

            SearchView.Customers = tempCustomers;
        }
    }
}
