using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
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.View.Detail;
using BeWo.View.Navigation.Sorter;
using BeWo.ViewModel;
using Microsoft.Win32;

namespace BeWo.View.Navigation
{
    /// <summary>
    ///     Interaktionslogik für PersonNavigationView.xaml
    /// </summary>
    public partial class PersonNavigationView
    {
        private IEnumerable<IFilterableDC> objectList;
        private IEnumerable<IFilterableDC> recentList;

        public PersonNavigationView()
        {
            InitializeComponent();

            mainNavigationView.Sorter = new PersonSorter();

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

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

        private bool mainNavigationView_ArchiveObject(IFilterableDC obj)
        {
            var dc = obj as CompactPersonDC;
            if (dc != null)
            {
                if (
                    MessageBox.Show(
                        "Wollen Sie die Person '" + dc.FirstName + " " + dc.LastName + "' wirklich archivieren?",
                        "Archivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoCustomerServiceAsync(
                        s =>
                            {
                                s.ArchivePerson(dc.PersonOid, dc.PersonVersion);
                                return dc;
                            },
                        cb => cb.PersonVersion++);

                    return true;
                }
            }

            return false;
        }

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

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            var dc = obj as CompactPersonDC;
            if (dc != null)
            {
                if (
                    MessageBox.Show(
                        "Wollen Sie die Person '" + dc.FirstName + " " + dc.LastName + "' wirklich löschen?", "Löschen",
                        MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.DeactivatePerson(dc.PersonOid, dc.PersonVersion));
                    return true;
                }
            }

            return false;
        }

        private void mainNavigationView_ExcelExport(object sender, EventArgs<IEnumerable<IFilterableDC>> e)
        {

			//          string path = BeWoApp.LoginControl.GetAndCreateTempDataPath() + "\\Personen.xls";

			var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Personen.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.PrepareExcelFilePersonExport(mainNavigationView.DownloadLinkEngine.ExcelFileId,
                                                   e.Data.Cast<CompactPersonDC>().Select(c => c.PersonOid).ToList()),
                    sf.FileName));
        }

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            var dc = obj as CompactPersonDC;
            if (dc != null)
            {
                VMFactory.CreatePersonVMAsync(dc.PersonOid, cb => this.Dispatch(() => MainControl.NavigateTo(new PersonView(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.GetAllPersonsByTypeCompact(PersonType.Others), r => this.Dispatch(delegate
                        {
                            objectList = r;
                            mainNavigationView.ShowSearchResult(objectList);
                        }));
                ServiceFacade.DoCustomerServiceAsync(s => s.GetLastOpenedPersons(), r => this.Dispatch(delegate
                    {
                        recentList = r;
                        mainNavigationView.ShowHistory(recentList);
                    }));
            }
            else
            {
                mainNavigationView.ShowSearchResult(objectList);
                mainNavigationView.ShowHistory(recentList);
            }
        }

        private void MainNavigationView_OnOpenMailMergeWindow(List<IFilterableDC> allPersons, IFilterableDC selectedPerson)
        {
            var mmw = new MailMergeWindow(this, typeof(PersonDC), objectList.ToList(), selectedPerson)
            {
                Sorter = new PersonSorter()
            };
            mmw.Show();
        }

	    public void ReactivatePerson(CompactPersonDC person)
	    {
			if (MessageBox.Show("Wollen Sie die Person '" + person.FirstName + " " + person.LastName + "' wirklich reaktivieren?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
			{
				return;
			}

			ServiceFacade.DoCustomerServiceAsync(s =>
			{
				s.ReactivatePerson(person.PersonOid, person.Version);
				return person;
			}, cb => cb.PersonVersion++);

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