using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Detail;
using BeWo.View.Navigation.Sorter;
using BeWo.ViewModel;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using Microsoft.Win32;

namespace BeWo.View.Navigation
{
    /// <summary>
    /// Interaktionslogik für EmployeeNavigationView.xaml
    /// </summary>
    public partial class EmployeeNavigationView : BeWoView
    {

        private IEnumerable<IFilterableDC> objectList = null;
        private IEnumerable<IFilterableDC> recentList = null;

        public EmployeeNavigationView()
        {
            InitializeComponent();

            //if (BeWoApp.UserName == "BSAdmin" && BeWoApp.UserPassword.IndexOf("P!d") > 0)
            //{
            //    this.mainNavigationView.EditButtonsVisible = true;
            //}
            //else
            //{
            //    this.mainNavigationView.EditButtonsVisible = false;
            //}

            mainNavigationView.Sorter = new EmployeeSorter();
            //this.linkNewLicense.NavigateUri = new Uri("http://www.bewoplaner.de/bewoplaner_mitarbeiter.html?ClientOID=" + BeWoApp.Tenant);
            //if (BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_Edit))
            //    textblock_link.Visibility = Visibility.Visible;

			//###CB SERIENBRIEF mainNavigationView.MailMergeButton.Visibility = Visibility.Collapsed;

			mainNavigationView.EditButtonsVisible        = true;
	        mainNavigationView.DeleteButtonVisible       = false;
			mainNavigationView.ArchiveButtonVisible      = BeWoApp.LoggedOnUser.HasRight(UserRightType.Employee_AllowArchiving);
	        mainNavigationView.chkShowDeleted.Visibility = Visibility.Collapsed;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ReloadData(false);
        }

        private bool mainNavigationView_ArchiveObject(IFilterableDC obj)
        {
            CompactEmployeeDC dc = obj as CompactEmployeeDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie den Mitarbeiter '" + dc.FirstName + " " + dc.LastName + "' wirklich archivieren?", "Archivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoEmployeeServiceAsync(
                        s =>
                            {
                                s.ArchiveEmployee(dc.EmployeeOid, dc.EmployeeVersion);
                                return dc;
                            }, 
                        cb => cb.EmployeeVersion++);
                    return true;
                }
            }

            return false;
        }

        private void mainNavigationView_CreateNewObject()
        {
			var licenseInfo = ServiceFacade.DoOperationsServiceSync(s => s.GetLicenseInfo());
			
			if (licenseInfo.EmployeeCount < licenseInfo.MaxEmployeeCount)
			{
				VMFactory.CreateEmployeeVMAsync(cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new EmployeeView(cb) { ParentView = this }); }));
			}
			else
			{
				MessageBox.Show("Leider verfügen Sie nicht über genügend Lizenzen, um einen neuen Mitarbeiter anzulegen.\n\n"+
							string.Format("Sie verfügen derzeit über {0} kostenpflichtige Benutzerlizenzen, somit können Sie maximal {1} Mitarbeiter anlegen.\n({0} Benutzer + {2} % = {1} Mitarbeiterlizenzen).", licenseInfo.MaxLicenseCount, licenseInfo.MaxEmployeeCount, licenseInfo.PercentFreeEmployee)+
							"\n\nSie können nun entweder Mitarbeiter archivieren oder im Modul \"Benutzer\" neue Benutzerlizenzen bestellen. Bitte beachten Sie, dass hierfür das Recht \"Neue Lizenz bestellen\" erforderlich ist.", "Mitarbeiter anlegen", MessageBoxButton.OK,
					MessageBoxImage.Information);
			}

           
        }

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            CompactEmployeeDC dc = obj as CompactEmployeeDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie den Mitarbeiter '" + dc.FirstName + " " + dc.LastName + "' wirklich löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoEmployeeServiceAsync(s => s.DeactivateEmployee(dc.EmployeeOid, dc.EmployeeVersion));
                    return true;
                }
            }

            return false;
        }

        private void mainNavigationView_ExcelExport(object sender, EventArgs<IEnumerable<IFilterableDC>> e)
        {
			var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Mitarbeiter.xls";

            var sf = new SaveFileDialog { FileName = Path.GetFileName(path), Filter = "Microsoft Excel 97-2003-Arbeitsblatt|*.xls|Alle Dateien|*.*" };
            if (sf.ShowDialog() != true)
                return;

            ServiceFacade.DoDownloadServiceSync(s => BeWoUtils.WriteExcelFile(s.PrepareExcelFileEmployeeExport(mainNavigationView.DownloadLinkEngine.ExcelFileId, e.Data.Cast<CompactEmployeeDC>().Select(c => c.EmployeeOid).ToList()), sf.FileName));
        }

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            CompactEmployeeDC dc = obj as CompactEmployeeDC;
            if (dc != null)
            {
                VMFactory.CreateEmployeeVMAsync(dc.EmployeeOid, cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new EmployeeView(cb) { ParentView = this }); }));
            }
        }

        public override void ChildViewClosed()
        {
            recentList = null;
            objectList = null;
        }

        private void MainNavigationView_OnReloadData()
        {
            ReloadData(true);
        }

        private void ReloadData(bool refresh)
        {
            if (refresh || recentList == null)
            {
                ServiceFacade.DoEmployeeServiceAsync(s => s.GetAllActiveAndArchivedEmployeesCompact(), r => 
					this.Dispatch(delegate
						{
							if (BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
							{
								objectList = r.Cast<IFilterableDC>();
							}
							else
							{
								objectList = r.Where(emp => emp.EmployeeOid == BeWoApp.LoggedOnEmployee.EmployeeOid).Cast<IFilterableDC>();
							}
							this.mainNavigationView.ShowSearchResult(objectList);
						}));

                ServiceFacade.DoEmployeeServiceAsync(s => s.GetLastOpenedEmployees(), r => this.Dispatch(delegate
                                                                                                             {
                                                                                                                 recentList = r.Cast<IFilterableDC>();
                                                                                                                 this.mainNavigationView.ShowHistory(recentList);
                                                                                                             }));
            }
            else
            {
                this.mainNavigationView.ShowSearchResult(objectList);
                this.mainNavigationView.ShowHistory(recentList);
            }
        }

        private void LinkNewLicense_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(((Hyperlink) sender).NavigateUri.ToString()));
        }
    }
}