using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Detail;
using BeWo.ViewModel;

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

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

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

        public IEnumerable<IFilterableDC> ObjectList { get { return objectList; } set { objectList = value; } }
        public IEnumerable<IFilterableDC> RecentList { get { return recentList; } set { recentList = value; } }

        public UserNavigationView()
        {
            this.InitializeComponent();
	        if (BeWoApp.LoggedOnUser.HasRight(UserRightType.User_AllowOrderLicense))
	        {
		        this.linkNewLicense.NavigateUri = new Uri(ServiceFacade.DoOperationsServiceSync(s => s.GetLicenseOrderUrl()));
	        }
	        else
	        {
		        textblock_link.Visibility = Visibility.Collapsed;
	        }
			//###CB SERIENBRIEF mainNavigationView.MailMergeButton.Visibility = Visibility.Collapsed;
        }

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

        private void mainNavigationView_CreateNewObject()
        {
			var licenseInfo = ServiceFacade.DoOperationsServiceSync(s => s.GetLicenseInfo());

	        if (licenseInfo.LicenseInUseCount < licenseInfo.MaxLicenseCount)
	        {
		        VMFactory.CreateUserVMAsync(
			        cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new UserView(cb) {ParentView = this}); }));
	        }
	        else
	        {
		        MessageBox.Show("Leider verfügen Sie nicht über genügend Lizenzen, um einen neuen Benutzer anzulegen.\n\n"+
							string.Format("Sie verfügen derzeit über {0} kostenpflichtige Benutzerlizenzen.", licenseInfo.MaxLicenseCount)+
							"\n\nSie können nun entweder Benutzer löschen oder neue Benutzerlizenzen bestellen. Bitte beachten Sie, dass hierfür das Recht \"Neue Lizenz bestellen\" erforderlich ist.", "Benutzer anlegen", MessageBoxButton.OK,
					MessageBoxImage.Information);


	        }

        }

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            CompactUserDC dc = obj as CompactUserDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie den Benutzer '" + dc.LoginName + "' wirklich löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoUserServiceAsync(s => s.DeactivateUser(dc.UserOid, dc.UserVersion), true);
                    return true;
                }
            }

            return false;
        }

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

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            CompactUserDC dc = obj as CompactUserDC;
            if (dc != null)
            {
                VMFactory.CreateUserVMAsync(dc.UserOid, cb => this.Dispatch(delegate { this.MainControl.NavigateTo(new UserView(cb) { ParentView = this }); }));
            }
        }

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

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

        internal void ReloadData(bool refresh)
        {
            if (refresh || recentList == null)
            {
                ServiceFacade.DoUserServiceAsync(s => s.GetAllUsersCompact(), r => this.Dispatch(delegate
                                                                                                     {
                                                                                                         objectList = r.Cast<IFilterableDC>();
                                                                                                         this.mainNavigationView.ShowSearchResult(objectList);
                                                                                                     }), true);

                ServiceFacade.DoUserServiceAsync(s => s.GetLastOpenedUsers(), r => this.Dispatch(delegate
                                                                                                     {
                                                                                                         recentList = r.Cast<IFilterableDC>();
                                                                                                         this.mainNavigationView.ShowHistory(recentList);
                                                                                                     }), true);
            }
            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((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
        }
    }
}