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

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

using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.ViewModel;

namespace BeWo.View.Controls
{
    /// <summary>
    /// Interaktionslogik für MultiAddServGroupOfPeopleSelectionControl.xaml
    /// </summary>
    public partial class MultiAddServGroupOfPeopleSelectionControl : UserControl, INotifyPropertyChanged
    {
        public event EventHandler EditGroupButtonClicked;
        
        private ObservableSortCollection<AdditionalServiceGroupMember> _GroupMemberList;

        public ObservableSortCollection<AdditionalServiceGroupMember> GroupMemberList
        {
            get { return _GroupMemberList ?? (_GroupMemberList = new ObservableSortCollection<AdditionalServiceGroupMember>()); }
            set
            {
                _GroupMemberList = value; UpdateCustomerList(); 
                
                if (SearchView.ObjectList == null)
                    return;

                var SearchList = SearchView.ObjectList;

                foreach (var groupmember in GroupMemberList.Where(groupmember => SearchList.Contains(groupmember.Customer)))
                    SearchList.Remove(groupmember.Customer);

                SearchView.ObjectList = null;
                SearchView.ObjectList = SearchList;
            }
        }

        private AdditionalServiceGroupOfPeopleDC _CurrentGroup;
        public AdditionalServiceGroupOfPeopleDC CurrentGroup { 
            get { return _CurrentGroup ?? (_CurrentGroup = new AdditionalServiceGroupOfPeopleDC{CustomerList = new List<CompactCustomerDC>()}); }
            set 
            {
                _CurrentGroup = value;
                GroupMemberList = value == null ? null : value.GetGroupMembers();
                OnPropertyChanged("CurrentGroup");
            } 
        }

        public MultiAddServGroupOfPeopleSelectionControl()
        {
            InitializeComponent();
            DataContext = this;
            AddServGroupSearchView.EditGroupButtonClicked += GroupSearchView_EditGroupButtonClicked;
            UpdateCustomerList();
        }

        private void UpdateCustomerList()
        {
            if (ListBoxCustomers == null)
                return;

            GroupMemberList.Sort((x, y) => x.Customer.Name.CompareTo(y.Customer.Name));
            ListBoxCustomers.ItemsSource = GroupMemberList;

            LabelGroupName.Content = CurrentGroup != null ? CurrentGroup.Name : "<Keine Gruppe ausgewählt>";
        }

        void GroupSearchView_EditGroupButtonClicked(object sender, EventArgs e)
        {
            if (EditGroupButtonClicked == null) 
                return;

            EditGroupButtonClicked(sender, e);
            PopupAdditionalServiceGroupsOfPeople.IsOpen = false;
        }

        private void AdditionalServiceGroupOfPeopleSearchView_ItemSelected(object sender, EventArgs<AdditionalServiceGroupOfPeopleDC> e)
        {
            PopupAdditionalServiceGroupsOfPeople.IsOpen = false;

            CurrentGroup = e.Data;
            GroupMemberList = e.Data.GetGroupMembers();
        }

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

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

            CurrentGroup.CustomerList.Add(e.Data);
            var Swap = CurrentGroup;
            CurrentGroup = Swap;
        }

        private void btnAddCustomer_Click(object sender, RoutedEventArgs e)
        {
            ServiceFacade.DoCustomerServiceAsync(s => s.GetAllActiveCustomersCompact(true, BeWoApp.LoggedOnUser.Employee.EmployeeOid),
                r =>
                    {
                        var list = r.ToList();

                        this.Dispatch(delegate
                        {
                            var SearchList = list;

                            foreach (var groupmember in GroupMemberList.Where(groupmember => SearchList.Contains(groupmember.Customer)))
                                SearchList.Remove(groupmember.Customer);

                            SearchView.ObjectList = SearchList;
                        });
                    });

            PopupCustomers.IsOpen = true;
        }

        private void listBoxCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e) { }

        private void btnAddGroup_Click(object sender, RoutedEventArgs e)
        {
            ServiceFacade.DoOperationsServiceAsync(s => s.GetAllAdditionalServiceGroupOfPeople(),
                r =>
                {
                    var list = r.ToList();
                    this.Dispatch(delegate { AddServGroupSearchView.GroupOfPeoples = list; });
                });

            PopupAdditionalServiceGroupsOfPeople.IsOpen = true;
        }

        private void btnRemoveCustomer_Click(object sender, RoutedEventArgs e)
        {
            var customer = ((Button)sender).Tag as AdditionalServiceGroupMember;

            if (CurrentGroup == null || !CurrentGroup.CustomerList.Contains(customer.Customer))
                return;

            CurrentGroup.CustomerList.Remove(customer.Customer);
            var swap = CurrentGroup;
            CurrentGroup = swap;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        internal void UpdateCustomers(CompactCustomerDC updatedCustomer)
        {
            var list = GroupMemberList;

            foreach (var item in list.Where(item => item.Customer.Equals(updatedCustomer)))
            {
                item.Customer = new CompactCustomerDC();
                item.Customer = updatedCustomer;
            }

            UpdateCustomerList();
        }

        private void DoubleClickHandler(object sender, MouseButtonEventArgs e)
        {   // Doppelklick auf den ToggleButton abfangen
            var dc = (((ListBoxItem)sender).Content as AdditionalServiceGroupMember).Customer;

            if (dc == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View))
                return;

            VMFactory.CreateCustomerVMAsync(dc.CustomerOid,
                    cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, BeWoView>(cb, null, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews(dc)))));
        }
    }
}
