using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Detail;
using BeWo.View.Navigation.Filter;
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 BeWo.Core.Service;
using Microsoft.Win32;

namespace BeWo.View.Navigation
{
    /// <summary>
    /// Interaktionslogik für SupportConceptNavigationView.xaml
    /// </summary>
    public partial class SupportConceptNavigationView : BeWoView
    {
        private readonly CheckBox chkShowOnlyMySCs;

        private readonly CheckBox chkShowOnlyTeamSCs;

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

        public SupportConceptNavigationView()
        {
            this.InitializeComponent();

            this.mainNavigationView.Sorter = new SupportConceptSorter();
            this.mainNavigationView.ArchiveButtonVisible = BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_AllowArchiving);
            this.mainNavigationView.ShowArchivedObjectsVisible = true;

            this.chkShowOnlyMySCs = new CheckBox();
            this.chkShowOnlyMySCs.FontSize = 12;
            this.chkShowOnlyMySCs.Margin = new Thickness(10, 0, 0, 0);
            this.chkShowOnlyMySCs.Content = "Nur meine Hilfepläne anzeigen";

            this.chkShowOnlyTeamSCs = new CheckBox();
            this.chkShowOnlyTeamSCs.FontSize = 12;
            this.chkShowOnlyTeamSCs.Margin = new Thickness(10, 0, 0, 0);
            this.chkShowOnlyTeamSCs.Content = "Nur Hilfepläne meines Teams anzeigen";

            this.chkShowOnlyMySCs.VerticalAlignment = VerticalAlignment.Center;
            this.chkShowOnlyTeamSCs.VerticalAlignment = VerticalAlignment.Center;

            Brush b = this.FindResource("MainGroupBoxForegroundBrush") as Brush;
            if (b != null)
            {
                this.chkShowOnlyMySCs.Foreground = b;
                this.chkShowOnlyTeamSCs.Foreground = b;
            }

            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_ViewAllSupportConcepts) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.ViewAll))
            {
                this.chkShowOnlyMySCs.IsChecked = true;
                this.chkShowOnlyMySCs.IsEnabled = false;
            }
            else
            {
                this.chkShowOnlyMySCs.IsChecked = BeWoApp.AppSettings.ShowOnlyMySupportConcepts;
            }

            // if (BeWoApp.LoggedOnUser.Employee.IsTeamLeader)
            // {
            // chkShowOnlyTeamSCs.Visibility = Visibility.Visible;
            // }
            // else
            // {
            this.chkShowOnlyTeamSCs.Visibility = Visibility.Collapsed;

            // }
            this.chkShowOnlyMySCs.Click += this.chkShowOnlyMySCs_Click;
            this.chkShowOnlyTeamSCs.Click += this.chkShowOnlyTeamSCs_Click;
            this.mainNavigationView.AddControlToSortPanel(this.chkShowOnlyMySCs);

            this.UpdateCustomFilter();

	        if (BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_Create))
	        {
		        mainNavigationView.btnCopy.Visibility = Visibility.Visible;
	        }
        }

        private CustomFilter CreateNewCustomFilter()
        {
            SupportConceptNavigationFilter filter = new SupportConceptNavigationFilter();
            filter.ShowOnlyMySupportConcepts = this.chkShowOnlyMySCs.IsChecked.Value;
            filter.ShowOnlyTeamSupportConcepts = this.chkShowOnlyTeamSCs.IsChecked.Value;
            return filter;
        }

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

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

        private void chkShowOnlyMySCs_Click(object sender, RoutedEventArgs e)
        {
            // chkShowOnlyTeamSCs.IsChecked = false;
            BeWoApp.AppSettings.ShowOnlyMySupportConcepts = this.chkShowOnlyMySCs.IsChecked.Value;
            BeWoApp.SaveAppSettings();

            this.UpdateCustomFilter();
        }

        private void chkShowOnlyTeamSCs_Click(object sender, RoutedEventArgs e)
        {
            this.chkShowOnlyMySCs.IsChecked = false;
            this.UpdateCustomFilter();
        }

        private bool mainNavigationView_ArchiveObject(IFilterableDC obj)
        {
            CompactSupportConceptDC dc = obj as CompactSupportConceptDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie den Hilfeplan wirklich archivieren?", "Archivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    ServiceFacade.DoCustomerServiceAsync(
                        s =>
                            {
                                s.ArchiveSupportConcept(dc.SupportConceptOid, dc.SupportConceptVersion);
                                return dc;
                            }, 
                        cb => cb.SupportConceptVersion ++);
                    Cache.GetInstance().ClearSupportConceptTree();
                    return true;
                }
            }

            return false;
        }

        private void mainNavigationView_CreateNewObject()
        {
            //VMFactory.CreateSupportConceptVMAsync(cb => this.Dispatch(() => this.MainControl.NavigateTo(new SupportConceptView2(cb) { ParentView = this })));
            VMFactory.CreateSupportConceptVMAsync(cb => this.Dispatch(() => this.MainControl.NavigateTo(new SupportConceptView(cb) { ParentView = this })));
            
        }

        private bool mainNavigationView_DeleteObject(IFilterableDC obj)
        {
            var dc = obj as CompactSupportConceptDC;
            if (dc != null)
            {
                if (MessageBox.Show("Wollen Sie den Hilfeplan wirklich löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    var list = ServiceFacade.DoOperationsServiceSync(s => s.GetSupportConceptInfosForSupportConceptOid(dc.SupportConceptOid));
                    var delete = true;

                    if (list != null && list.Count > 0)
                    {
                        var containsServiceRecords = false;
                        foreach (var info in list.Where(info => info.RecordedHours > 0))
                        {
	                        containsServiceRecords = true;
                        }

                        if (containsServiceRecords)
                        {
                            if (MessageBox.Show("Für den gewählten Hilfeplan wurden bereits Leistungen hinterlegt.\n Möchten Sie wirklich fortfahren und den Hilfeplan löschen?", "Löschen", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                            {
                                delete = false;
                            }
                        }

                    }
                    if (delete)
                    {
                        ServiceFacade.DoCustomerServiceAsync(s =>
                        {
	                        s.DeactivateSupportConcept(dc.SupportConceptOid, dc.SupportConceptVersion);
	                        return dc;
                        }, cb => dc.Version++);

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

                    
                }
            }

            return false;
        }

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

        private void mainNavigationView_OpenObject(IFilterableDC obj)
        {
            var dc = obj as CompactSupportConceptDC;
            if (dc != null)
            {
                VMFactory.CreateSupportConceptVMAsync(dc.SupportConceptOid, cb => this.Dispatch(() => MainControl.NavigateTo(new SupportConceptView(cb) {ParentView = this})));
                //VMFactory.CreateSupportConceptVMAsync(dc.SupportConceptOid, cb => this.Dispatch(
                //    () => this.MainControl.NavigateTo(new SupportConceptView2(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.GetAllSupportConceptsCompact(BeWoApp.LoggedOnUser.Employee.EmployeeOid), r => this.Dispatch(delegate
		        {
			        objectList = r;
			        mainNavigationView.ShowSearchResult(objectList);
		        }));

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

        private void MainNavigationView_OnOpenMailMergeWindow(List<IFilterableDC> allSupportConcepts, IFilterableDC selectedSupportConcept)
        {
            var mmw = new MailMergeWindow(this, typeof(SupportConceptDC), objectList.ToList(), selectedSupportConcept)
            {
                Sorter = new SupportConceptSorter()
            };
            mmw.Show();
        }

	    public void MainNavigationView_OnReactivateObject(CompactSupportConceptDC selectedSupportConcept)
	    {
			if (MessageBox.Show("Wollen Sie den Hilfeplan wirklich reaktivieren?", "Reaktivieren", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
			{
				return;
			}

			ServiceFacade.DoCustomerServiceAsync(s =>
			{
				s.ReactivateSupportConcept(selectedSupportConcept.SupportConceptOid, selectedSupportConcept.Version);
				return selectedSupportConcept;
			}, cb => cb.SupportConceptVersion++);

			Cache.GetInstance().ClearSupportConceptTree();

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

	    private void MainNavigation_CopyObject(IFilterableDC obj)
	    {
		    var csc = (CompactSupportConceptDC) obj;
		    var copy = new SupportConceptDC();

			ServiceFacade.DoCustomerServiceAsync(s => s.LoadSupportConcept(csc.SupportConceptOid), cb =>
			{
				copy.ActivationType     = ActivationTypeId.Active;
				copy.Conference         = cb.Conference;
				copy.ConferenceVenue    = cb.ConferenceVenue;
				copy.ConsultingNeeded   = cb.ConsultingNeeded;
				copy.Customer           = cb.Customer;
				copy.Notice             = cb.Notice;
				copy.Originator         = cb.Originator;
				copy.ServiceAccountings = new List<ServiceAccountingDC>();

				foreach (var kategorie in cb.ServiceAccountings)
				{
					var kat = new ServiceAccountingDC
					{
						AccountingInterval = kategorie.AccountingInterval,
						BillableAmount     = kategorie.BillableAmount,
						IsDefault          = kategorie.IsDefault,
						ServiceDescription = kategorie.ServiceDescription
					};

					copy.ServiceAccountings.Add(kat);
				}

				foreach (var kt in cb.CostBearerRelations)
				{
					var rel = new SupportConceptCostBearerRelDC
					{
						CostBearer              = kt.CostBearer, 
						CostBearerContactPerson = kt.CostBearerContactPerson, 
						CustomerReferenceNumber = kt.CustomerReferenceNumber, 
						Notice                  = kt.Notice, 
						Status                  = CostBearer2SupportConceptStatus.Created,
						SupportConcept          = kt.SupportConcept,
						ApprovalPeriodList      = new List<SupportConceptApprovalPeriodDC> { new SupportConceptApprovalPeriodDC
						{
							IsApprovedBEShifting = true, 
							IsApprovedFixedAmountShifting = true, 
							ApprovedBEInterval = SupportConceptApprovalInterval.Weekly
						}}
					};

					copy.CostBearerRelations.Add(rel);
				}
				
				copy.Goals = new List<ValueListEntryDC>(cb.Goals);

				VMFactory.CreateSupportConceptVMAsync(copy, sc => this.Dispatch(() => 
					this.MainControl.NavigateTo(new SupportConceptView(sc) { ParentView = this })), true);
				//ServiceFacade.DoCustomerServiceAsync(s2 => s2.InsertNewSupportConcept(copy), l => this.Dispatch(() => ReloadData(true)));
			});
	    }
    }
}