using System;
using System.Linq;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using BeWo.Controls;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.ViewModel;

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

namespace BeWo.View.Detail
{
    public partial class TeamView
    {
        private TeamVM _ViewModel;

        private EventHandler<MouseButtonEventArgs> DoubleClickEventHandler;

        public TeamView(TeamVM pViewModel)
        {
            DoubleClickEventHandler += ListBox_OnPreviewMouseDoubleClick;

            InitializeComponent();

            var s = teamViewMainGrid.Resources["myNavigationListItemStyle"] as Style;
            employeesearchview.ResultListBox.ItemContainerStyle = s;

            ViewModel = pViewModel;

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.DocumentsAllowViewAll) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.DokumenteTeams))
			{
				tabitem_documents.Visibility = Visibility.Collapsed;
			}
        }

        public override bool IsDirty
        {
            get
            {
                return ViewModel != null && ViewModel.IsDirty;
            }
        }

        public override string Title
        {
            get
            {
                return "Teams";
            }
        }

        internal TeamVM ViewModel
        {
            get
            {
                return _ViewModel;
            }

            set
            {
                _ViewModel = value;
                DataContext = value;
            }
        }

        protected override UserRightType[] GetSaveDemands()
        {
            return ViewModel.IsNew ? new[] { UserRightType.CreateAll, UserRightType.TeamView_Create } : new[] { UserRightType.EditAll, UserRightType.TeamView_Edit };
        }

        protected override void Save()
        {
            var lDC = ViewModel.CommitToDataContract();
            try
            {
                if (ViewModel.IsNew)
                {
                    IsDoneWithInsertOrUpdate = false;
                    ServiceFacade.DoEmployeeServiceAsync(s => s.InsertNewTeam(lDC), ReloadViewModel);
                }
                else
                {
                    IsDoneWithInsertOrUpdate = false;
                    ServiceFacade.DoEmployeeServiceAsync(s => s.UpdateTeam(lDC), ReloadViewModel);
                }

                Cache.GetInstance().ClearEmployees();
                BeWoApp.MainControl.ResetView(UIContext.Team);
            }
            catch (FaultException<BeWoFault>)
            {
                MessageBox.Show("Dieser Datensatz wurde in der Zwischenzeit von einem anderen Benutzer geändert. Klicken Sie Ok um den Datansatz erneut zu laden. Ihre Änderungen gehen dabei leider verloren.");
                ReloadViewModel(lDC.TeamOid.Value);
            }
        }

        private void EmployeeSearchView_EmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popup_employee.IsOpen = false;
            ViewModel.Leader      = e.Data;
        }

        private void PopUpEdit_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_employee.IsOpen = true;
        }

        private void ReloadViewModel(long pOid)
        {
            VMFactory.CreateTeamVMAsync(pOid, cb => this.Dispatch(delegate
            {
                ViewModel = cb;

                if (ModalEditViewUpdateCallback != null)
                {
                    ModalEditViewUpdateCallback();
                }
            }));

            IsDoneWithInsertOrUpdate = true;
        }

        public void ReloadViewModel()
        {
            ReloadViewModel(ViewModel.DataContract.TeamOid.Value);
        }

        private void button_add_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.Member.AddRange(employeesearchview.SelectedItems.Where(em => !ViewModel.Member.Contains(em)));
        }

        private void button_remove_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.Member.Remove((CompactEmployeeDC)((Button)sender).Tag);
        }

        private void tabitem_documents_Selected(object sender, RoutedEventArgs e)
        {
            if (ViewModel.IsNew)
            {
                MessageBox.Show("Bevor zu einem Datensatz Dokumente hinterlegt werden können, muss dieser gespeichert werden.", "Erst speichern bitte", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (tabitem_documents.Content == null)
            {
                tabitem_documents.Content = new BeWoFileView(TableID.Team, ViewModel.DataContract.TeamOid.Value);
            }
        }

        private void Popupedit_leader_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || ViewModel.Leader == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            VMFactory.CreateEmployeeVMAsync(ViewModel.Leader.EmployeeOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, TeamView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(ViewModel.Leader)))));
        }

        private void DoubleClickHandler(object sender, MouseButtonEventArgs e)
        {
            var selectedEmployee = ((ListBoxItem) sender).Content as CompactEmployeeDC;

            if (selectedEmployee == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            VMFactory.CreateEmployeeVMAsync(selectedEmployee.EmployeeOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, TeamView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(selectedEmployee)))));
        }

        private void ListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var employee = ((ListBoxItem)sender).Content as CompactEmployeeDC;
            
            if (employee == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            VMFactory.CreateEmployeeVMAsync(employee.EmployeeOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, TeamView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(employee)))));
        }
    }
}