using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Navigation;

using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Detail;
using BeWo.View.Navigation.Filter;
using BeWo.View.Navigation.Sorter;
using BeWo.ViewModel;
using BeWo.Core.Service;

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 CustomerNavigationView.xaml
    /// </summary>
    public partial class CustomerNavigationView
    {
        private readonly CheckBox chkShowOnlyMyCustomers;

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

        public CustomerNavigationView()
        {
            InitializeComponent();

            mainNavigationView.Sorter = new CustomerSorter();
            mainNavigationView.ArchiveButtonVisible =
                BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_AllowArchiving);
            mainNavigationView.ShowArchivedObjectsVisible = true;

            chkShowOnlyMyCustomers = new CheckBox
                {
                    FontSize = 12,
                    Margin = new Thickness(10, 0, 0, 0),
                    Content = "Nur meine Klienten anzeigen",
                    VerticalAlignment = VerticalAlignment.Center
                };

            var b = FindResource("MainGroupBoxForegroundBrush") as Brush;
            if (b != null)
            {
                chkShowOnlyMyCustomers.Foreground = b;
            }

            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View) &&
                !BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll))
            {
                chkShowOnlyMyCustomers.IsChecked = true;
                chkShowOnlyMyCustomers.IsEnabled = false;
            }
            else
            {
                chkShowOnlyMyCustomers.IsChecked = BeWoApp.AppSettings.ShowOnlyMyClients;
            }

            chkShowOnlyMyCustomers.Click += chkShowOnlyMyCustomerss_Click;
            mainNavigationView.AddControlToSortPanel(chkShowOnlyMyCustomers);

            UpdateCustomFilter();
        }

        private CustomFilter CreateNewCustomFilter()
        {
            var filter = new CustomerNavigationFilter {ShowOnlyMyCustomers = chkShowOnlyMyCustomers.IsChecked != null && chkShowOnlyMyCustomers.IsChecked.Value};

            return filter;
        }

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

        private void UpdateCustomFilter()
        {
            mainNavigationView.CustomFilter = CreateNewCustomFilter();
        }

        private void chkShowOnlyMyCustomerss_Click(object sender, RoutedEventArgs e)
        {
            if (chkShowOnlyMyCustomers.IsChecked != null)
                BeWoApp.AppSettings.ShowOnlyMyClients = chkShowOnlyMyCustomers.IsChecked.Value;
            BeWoApp.SaveAppSettings();

            UpdateCustomFilter();
        }

        private bool mainNavigationView_ArchiveObject(IFilterableDC obj)
        {
            var cdc = obj as CompactCustomerDC;
            if (cdc != null)
            {
                if (MessageBox.Show("Wollen Sie den Klient '" + cdc.FirstName + " " + cdc.LastName + "' wirklich archivieren?", "Archivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoCustomerServiceAsync(
                        s =>
                            {
                                s.ArchiveCustomer(cdc.CustomerOid, cdc.CustomerVersion);
                                return cdc;
                            }, 
                        cb => cb.CustomerVersion++);

                    Cache.GetInstance().ClearSupportConceptTree();
                    return true;
                }
            }

            return false;
        }

        private void mainNavigationView_CreateNewObject()
        {
            VMFactory.CreateCustomerVMAsync(cb => this.Dispatch(() => MainControl.NavigateTo(new CustomerView(cb) {ParentView = this})));
        }

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            var cdc = obj as CompactCustomerDC;
            if (cdc != null)
            {
                if (MessageBox.Show("Wollen Sie den Klient '" + cdc.FirstName + " " + cdc.LastName + "' wirklich löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {

                    CustomerInfoDC details = ServiceFacade.DoOperationsServiceSync(s => s.GetCustomerInfosForCustomerOid(cdc.CustomerOid));
                    bool delete = true;
                    if (details != null)
                    {
                        if (!string.IsNullOrEmpty(details.CurrentSupportConcept) && details.CurrentSupportConcept.ToLower() != "kein aktueller hilfeplan")
                        {
                            if (MessageBox.Show("Für Klient '" + cdc.FirstName + " " + cdc.LastName + "' wurde bereits ein Hilfeplan angelegt. Der Hilfeplan wird dadurch auch gelöscht!\n Möchten Sie wirklich fortfahren und den Klient löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                            {
                                delete = false;
                            }
                        }
                        
                    }
                    if (delete)
                    {
                        ServiceFacade.DoCustomerServiceAsync(
	                        s =>
	                        {
		                        s.DeactivateCustomer(cdc.CustomerOid, cdc.CustomerVersion);
		                        return cdc;
	                        }, cb => cb.CustomerVersion++);

                        Cache.GetInstance().ClearSupportConceptTree();
                        return true;
                    }
                }
            }

            return false;
        }

        private void mainNavigationView_ExcelExport(object sender, EventArgs<IEnumerable<IFilterableDC>> e)
        {
			var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Klienten.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.PrepareExcelFileCustomerExport(mainNavigationView.DownloadLinkEngine.ExcelFileId, e.Data.Cast<CompactCustomerDC>().Select(c => c.CustomerOid).ToList()), sf.FileName));
        }

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            var cdc = obj as CompactCustomerDC;
            if (cdc != null)
            {
                VMFactory.CreateCustomerVMAsync(cdc.CustomerOid, cb => this.Dispatch(() => MainControl.NavigateTo(new CustomerView(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.DoCustomerServiceAsync(
					s => s.GetAllCustomersCompact(BeWoApp.LoggedOnUser.Employee.EmployeeOid),
                    r => this.Dispatch(delegate
                                           {
                                               objectList = r;
                                               mainNavigationView.ShowSearchResult(objectList);
                                           }));

                ServiceFacade.DoCustomerServiceAsync(s => s.GetLastOpenedCustomers(),
                                                     r =>
                                                     this.Dispatch(
                                                         delegate
                                                             {
                                                                recentList = r;
                                                                mainNavigationView.ShowHistory(recentList);
                                                         }));
            }
            else
            {
                mainNavigationView.ShowSearchResult(objectList);
                mainNavigationView.ShowHistory(recentList);
            }
        }

	    private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
	    {
			BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Druckvorschau");
	    }

        private void MainNavigationView_OnOpenMailMergeWindow(List<IFilterableDC> allCustomers, IFilterableDC selectedCustomer)
        {
            var mmw = new MailMergeWindow(this, typeof(CustomerDC), objectList.ToList(), selectedCustomer)
                {
                    Sorter = new CustomerSorter()
                };
            mmw.Show();
        }

	    private void Hyperlink_Reaktivieren_Click(object sender, RoutedEventArgs e)
	    {
		    var cdc = (CompactCustomerDC) mainNavigationView.objectListBox.SelectedItem;

			if (MessageBox.Show("Wollen Sie den Klient '" + cdc.FirstName + " " + cdc.LastName + "' wirklich reaktivieren?", "Reaktivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
		    {
			    return;
		    }

		    ServiceFacade.DoCustomerServiceAsync(s =>
		    {
				s.ReactivateCustomer(cdc.CustomerOid, cdc.CustomerVersion);
			    return cdc;
		    }, cb => cb.CustomerVersion++);

			Cache.GetInstance().ClearSupportConceptTree();

			cdc.ActivationType = ActivationTypeId.Active;
			var context = mainNavigationView.objectListBox.DataContext;
			mainNavigationView.objectListBox.DataContext = null;
			mainNavigationView.objectListBox.DataContext = context;
	    }
    }
}