using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using BeWo.Core;
using BeWo.Core.Service;
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 OrganisationNavigationView.xaml
    /// </summary>
    public partial class OrganisationNavigationView : BeWoView
    {
        private IEnumerable<IFilterableDC> objectList = null;
        private IEnumerable<IFilterableDC> recentList = null;

        public OrganisationNavigationView()
        {
            this.InitializeComponent();

            this.mainNavigationView.Sorter = new OrganisationSorter();

			this.mainNavigationView.ArchiveButtonVisible =
				BeWoApp.LoggedOnUser.HasRight(UserRightType.Organisation_AllowArchiving);
			this.mainNavigationView.ShowArchivedObjectsVisible = true;
        }

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

        private void mainNavigationView_CreateNewObject()
        {
            VMFactory.CreateOrganisationVMAsync(cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new OrganisationView(cb) { ParentView = this }); }));
        }

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            CompactOrganisationDC dc = obj as CompactOrganisationDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie die Organisation '" + dc.Name + "' wirklich löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.DeactivateOrganisation(dc.OrganisationOid, dc.OrganisationVersion));
                    return true;
                }
            }

            return false;
        }

		private bool mainNavigationView_ArchiveObject(IFilterableDC obj)
		{
			CompactOrganisationDC dc = obj as CompactOrganisationDC;
			if (dc != null)
			{
				if (MessageBox.Show("Wollen Sie die Organisation '" + dc.Name + "' wirklich archivieren?", "Archivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
				{
					ServiceFacade.DoCustomerServiceAsync(
						s =>
						{
							s.ArchiveOrganisation(dc.OrganisationOid, dc.OrganisationVersion);
							return dc;
						},
						cb => cb.OrganisationVersion++);

					return true;
				}
			}

			return false;
		}


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

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            CompactOrganisationDC dc = obj as CompactOrganisationDC;
            if (dc != null)
            {
                VMFactory.CreateOrganisationVMAsync(dc.OrganisationOid, cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new OrganisationView(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.GetAllOrganisationsCompact(), r => this.Dispatch(delegate
                                                                                                                 {
                                                                                                                     objectList = r.Cast<IFilterableDC>();
                                                                                                                     this.mainNavigationView.ShowSearchResult(objectList);
                                                                                                                 }));

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

        private void MainNavigationView_OnOpenMailMergeWindow(List<IFilterableDC> allOrganisations, IFilterableDC selectedOrganisation)
        {
            var mmw = new MailMergeWindow(this, typeof(OrganisationDC), objectList.ToList(), selectedOrganisation)
            {
                Sorter = new OrganisationSorter()
            };
            mmw.Show();
        }

	    public void ReactivateOrganisation(CompactOrganisationDC organisation)
	    {
			if (MessageBox.Show("Wollen Sie die Organisation wirklich reaktivieren?", "Reaktivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
			{
				return;
			}

			ServiceFacade.DoCustomerServiceAsync(s =>
			{
				s.ReactivateOrganisation(organisation.OrganisationOid, organisation.Version);
				return organisation;
			}, cb => cb.OrganisationVersion++);

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