using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using BS.Shared.Core;
using System.Windows.Media;
using BS.Shared.Extensions;
using System.Collections;
using BeWo.Controls;
using BeWo.Core;
using System.Windows.Documents;
using BeWo.Core.Service;
using System.Windows.Threading;
using BeWo.QueryService;
using BeWo.View.Detail;
using BeWo.View.Master;
using BeWo.View.Report.FLSReport;
using BS.Shared.DataContracts.Compact;
using BS.Shared.DataContracts.Reports;
using BS.Shared.DataContracts;
using BeWo.ServiceProxy;
using BS.Shared;
using BeWo.ViewModel;
using Microsoft.Win32;


namespace BeWo.View.Report.Auslastung
{
    public partial class AuslastungReportView : BeWoView
    {
        internal CompactEmployeeDC _SelectedEmployee;
        internal CompactEmployeeDC _LastSelectedEmployee;

        internal CompactTeamDC _SelectedTeam;
        internal CompactTeamDC _LastSelectedTeam;

        private List<AuslastungListView> _AuslastungListViewList = null;
        private List<AuslastungAnalysisRootDC> _RootList;

        private DateTime _LastStartDate;
        private DateTime _LastEndDate;


        //private bool _FLSReportCreated = false;

        public AuslastungReportView()
        {
            InitializeComponent();

            DateTime startDate = DateTime.Now.AddMonths(-1);
            datePickerStartDate.DateTime = new DateTime(startDate.Year, startDate.Month, 1);
            datePickerEndDate.DateTime = DateTime.Now;

            //checkbox_showChart.IsChecked = false;
            //checkbox_showServiceRecords.IsChecked = false;
            //checkbox_sortBySubGroup.IsChecked = true;

            _SelectedEmployee = BeWoApp.LoggedOnUser.Employee;
            if (_SelectedEmployee != null)
                popupedit_employee.Text = _SelectedEmployee.ToString();


            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AuslastungAllEmployee_View))
            {
                popupedit_employee.IsEnabled = false;
                checkbox_all.IsChecked = false;
                checkbox_all.IsEnabled = false;
            }
            bool teamComboVisible = false;
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AuslastungTeam_View))
            {
                if (BeWoApp.LoggedOnUser.Employee.IsTeamLeader)
                
                {
                    lblEmployee.Visibility = Visibility.Collapsed;
                    popupedit_employee.Visibility = Visibility.Collapsed;
                    checkbox_all.Visibility = Visibility.Collapsed;
                    _SelectedEmployee = null;

                    teamComboVisible = true;
                    
                    InitTeamLeaderTeams();
                }
                
            }
            else
            {
                teamComboVisible = true;
            }

            if (!teamComboVisible)
            {
                popupedit_team.Visibility = Visibility.Collapsed;
                lblTeam.Visibility = Visibility.Collapsed;
            }

            //if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForCostbearer))
            //{
            //    radioCostbearerReport.IsEnabled = false;
            //}

            

            //checkbox_all_client.IsChecked = true;

            //InitServiceCategoryList();
            //InitGoals();
            DownloadLinkEngine = new DownloadLinkEngine();
            linkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();
        }

        private void InitTeamLeaderTeams()
        {
            if (BeWoApp.LoggedOnUser.Employee.LeadingTeamOids.Count == 1)
            {
                popupedit_team.IsEnabled = false;
                ServiceFacade.DoEmployeeServiceAsync(s => s.GetAllTeamsCompact(),
                r =>
                {
                    List<CompactTeamDC> list = r;
                    this.Dispatch(delegate
                    {
                        InitTeam(r);
                    });
                    
                });
                
            }
        }

        protected virtual void InitTeam(List<CompactTeamDC> teams)
        {
            foreach (var item in teams)
            {
                if (item.TeamOid == BeWoApp.LoggedOnUser.Employee.LeadingTeamOids[0])
                {
                    _SelectedTeam = item;
                    if (_SelectedTeam != null)
                        popupedit_team.Text = _SelectedTeam.ToString();

                }
            }
            
        }


        public DownloadLinkEngine DownloadLinkEngine { get; set; }

       

        private void EmployeeSearchView_CustomerSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            _SelectedEmployee = e.Data;
            popupedit_employee.Text = _SelectedEmployee.ToString();
            _SelectedTeam = null;
            popupedit_team.Text = "";
            popup_employee.IsOpen = false;
        }

        private void TeamSearchView_TeamSelected(object sender, EventArgs<CompactTeamDC> e)
        {
            _SelectedTeam = e.Data;
            popupedit_team.Text = _SelectedTeam.ToString();
            _SelectedEmployee = null;
            popupedit_employee.Text = "";
            popup_team.IsOpen = false;
        }

        private void button_generate_Click(object sender, RoutedEventArgs e)
        {
            ////bool fetchNew = false;

            //AuslastungConfig config = CreateAuslastungConfig();

            ////if (_FLSOverview == null)
            ////    fetchNew = true;
            ////if (_GoalsChanged)
            ////    fetchNew = true;
            ////_GoalsChanged = false;
            ////if (_SelectedEmployee == null && _LastSelectedEmployee != null)
            ////    fetchNew = true;
            ////else if (_SelectedEmployee != null && _LastSelectedEmployee == null)
            ////    fetchNew = true;
            ////else if (_SelectedEmployee != null && _LastSelectedEmployee != null && _LastSelectedEmployee.EmployeeOid != _SelectedEmployee.EmployeeOid)
            ////    fetchNew = true;
            ////else if (_LastStartDate != config.StartDate || _LastEndDate != config.EndDate)
            ////    fetchNew = true;

            ////else if (_SelectedCustomer == null && _LastSelectedCustomer != null)
            ////    fetchNew = true;
            ////else if (_SelectedCustomer != null && _LastSelectedCustomer == null)
            ////    fetchNew = true;
            ////else if (_SelectedCustomer != null && _LastSelectedCustomer != null && _LastSelectedCustomer.CustomerOid != _SelectedCustomer.CustomerOid)
            ////    fetchNew = true;
            ////else if (_LastStartDate != config.StartDate || _LastEndDate != config.EndDate)
            ////    fetchNew = true;
            
            ////if (fetchNew)
            ////{
            //long? teamOid = null;
            //long? employeeOid = null;
            //if (_SelectedTeam != null)
            //    teamOid = _SelectedTeam.TeamOid;
            //if (_SelectedEmployee != null)
            //    employeeOid = _SelectedEmployee.EmployeeOid;


            //ServiceFacade.DoAnalysisServiceAsync(s => s.GetAuslastungAnalysis(config.StartDate, config.EndDate, employeeOid, teamOid),
            //        r =>
            //        {
            //            this.Dispatch(delegate
            //            {
            //                CreateReportView(r, config);
            //            });
            //        });
           
                
            
            //_LastSelectedEmployee = _SelectedEmployee;
            //_LastSelectedTeam = _SelectedTeam;
            //_LastStartDate = config.StartDate;
            //_LastEndDate = config.EndDate;

            //UpdatePDFExportUri("");

            ////if (!config.ShowServiceRecords && config.ShowOnlyTotalRows)
            ////    textblock_link_pdfexport.Visibility = Visibility.Hidden;
            ////else
            ////    textblock_link_pdfexport.Visibility = Visibility.Visible;
            DoGenerate();
        }

        internal void DoGenerate()
        {
            //bool fetchNew = false;

            AuslastungConfig config = CreateAuslastungConfig();

            //if (_FLSOverview == null)
            //    fetchNew = true;
            //if (_GoalsChanged)
            //    fetchNew = true;
            //_GoalsChanged = false;
            //if (_SelectedEmployee == null && _LastSelectedEmployee != null)
            //    fetchNew = true;
            //else if (_SelectedEmployee != null && _LastSelectedEmployee == null)
            //    fetchNew = true;
            //else if (_SelectedEmployee != null && _LastSelectedEmployee != null && _LastSelectedEmployee.EmployeeOid != _SelectedEmployee.EmployeeOid)
            //    fetchNew = true;
            //else if (_LastStartDate != config.StartDate || _LastEndDate != config.EndDate)
            //    fetchNew = true;

            //else if (_SelectedCustomer == null && _LastSelectedCustomer != null)
            //    fetchNew = true;
            //else if (_SelectedCustomer != null && _LastSelectedCustomer == null)
            //    fetchNew = true;
            //else if (_SelectedCustomer != null && _LastSelectedCustomer != null && _LastSelectedCustomer.CustomerOid != _SelectedCustomer.CustomerOid)
            //    fetchNew = true;
            //else if (_LastStartDate != config.StartDate || _LastEndDate != config.EndDate)
            //    fetchNew = true;

            //if (fetchNew)
            //{
            long? teamOid = null;
            long? employeeOid = null;
            if (_SelectedTeam != null)
                teamOid = _SelectedTeam.TeamOid;
            if (_SelectedEmployee != null)
                employeeOid = _SelectedEmployee.EmployeeOid;


            ServiceFacade.DoAnalysisServiceAsync(s => s.GetAuslastungAnalysis(config.StartDate, config.EndDate, employeeOid, teamOid),
                    r =>
                    {
                        this.Dispatch(delegate
                        {
                            CreateReportView(r, config);
                        });
                    });



            _LastSelectedEmployee = _SelectedEmployee;
            _LastSelectedTeam = _SelectedTeam;
            _LastStartDate = config.StartDate;
            _LastEndDate = config.EndDate;

            UpdatePDFExportUri("");

            //if (!config.ShowServiceRecords && config.ShowOnlyTotalRows)
            //    textblock_link_pdfexport.Visibility = Visibility.Hidden;
            //else
            //    textblock_link_pdfexport.Visibility = Visibility.Visible;
        }

        private void CreateReportView(List<AuslastungAnalysisRootDC> list, AuslastungConfig config)
        {
            _RootList = list;
            _AuslastungListViewList = new List<AuslastungListView>();
            reportContent.Children.Clear();

            foreach (var item in list)
            {
                AuslastungListView view = new AuslastungListView(item, config);
                _AuslastungListViewList.Add(view);
                reportContent.Children.Add(view);
            }
            
            
        }

        private AuslastungConfig CreateAuslastungConfig()
        {
            AuslastungConfig config = new AuslastungConfig();

            //if (radioEmployeeReport.IsChecked != null && radioEmployeeReport.IsChecked.Value)
            //    config.ReportType = FLSReportType.Employee;
            //else if (radioCostbearerReport.IsChecked != null && radioCostbearerReport.IsChecked.Value)
            //    config.ReportType = FLSReportType.Costbearer;
            //else
            //    config.ReportType = FLSReportType.Customer;

            config.Employee = _SelectedEmployee;
            config.Team = _SelectedTeam;
            config.StartDate = datePickerStartDate.DateTime.Date;
            config.EndDate = datePickerEndDate.DateTime.Date.AddDays(1).AddSeconds(-1);
            //config.ShowChart = checkbox_showChart.IsChecked.Value;
            //config.ShowServiceRecords = checkbox_showServiceRecords.IsChecked.Value;
            //config.ShowOnlyTotalRows = !checkbox_sortBySubGroup.IsChecked.Value;
        
            //if (radioButtonIntervalDay.IsChecked.Value)
            //    config.DateInterval = DateInterval.Day;
            //else if (radioButtonIntervalWeek.IsChecked.Value)
            //    config.DateInterval = DateInterval.Week;
            //else if (radioButtonIntervalMonth.IsChecked.Value)
            //    config.DateInterval = DateInterval.Month;
            //else if (radioButtonIntervalQuarter.IsChecked.Value)
            //    config.DateInterval = DateInterval.Quarter;
            //else if (radioButtonIntervalYear.IsChecked.Value)
            //    config.DateInterval = DateInterval.Year;

            //List<ServiceCategoryDC> scList = new List<ServiceCategoryDC>();
            //foreach (var item in serviceCategoryList.Items)
            //{
            //    CheckBox chkBox = (CheckBox)item;
            //    if (chkBox.IsChecked.Value)
            //    {
            //        scList.Add((ServiceCategoryDC)chkBox.Content);
            //    }
            //}
            //config.ServiceCategories = scList;

            //if (treeview_Goals.Visibility == Visibility.Visible)
            //{
            //    List<long> oids = new List<long>();

            //    List<SupportConceptGoalDC> goals = treeview_Goals.ItemsSource as List<SupportConceptGoalDC>;

            //    foreach (var cat in goals)
            //    {
            //        foreach (var goal in cat.Children)
            //        {
            //            if (goal.IsChecked)
            //            {
            //                oids.Add(goal.GoalEntryDC.ValueListEntryOid.Value);
            //            }
            //        }
            //    }
            //    config.GoalOids = oids;
            //}

            return config;
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (popupedit_employee != null)
            {
                popupedit_employee.Text = "";
                _SelectedEmployee = null;
            }
        }

        //private void CheckBox_Customer_Checked(object sender, RoutedEventArgs e)
        //{
        //    if (popupedit_client != null)
        //    {
        //        popupedit_client.Text = "";
        //        _SelectedCustomer = null;
        //    }
        //}

        private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_employee.IsOpen = true;
        }

        private void popupedit_team_PopUpClick(object sender, RoutedEventArgs e)
        {
            popup_team.IsOpen = true;
        }
        private void linkPdfExport_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            //if (!_FLSReportCreated)
            //{
            //    e.Handled = true;

                //_FLSReportCreated = true;
                //linkPdfExport2.DoClick();

            if (_RootList != null && _RootList.Count > 0)
            {
                ServiceFacade.DoOperationsServiceSync(s => s.PrepareAuslastungReport(_RootList[0], BeWoApp.Tenant + "eoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid));
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
            }
            //}
            //else
            //{
            //    _FLSReportCreated = false;
            //}
        }

        private void UpdatePDFExportUri(String id)
        {
            //String url = BeWoApp.SiteOfOrigin.ToString()
            //            + "/ReportView.aspx?dcid="
            //            + BeWoApp.Tenant + "eoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid
            //            + "&tenant=" + BeWoApp.Tenant
            //            + "&username=" + BeWoApp.UserName
            //            + "&token=" + BeWoApp.LoggedOnUser.RC2Password
            //            + "&type=" + Utils.EnumName<ReportTypes>(ReportTypes.AuslastungReport);
            
            //url = BeWoWpfUtils.GetHTMLEncodedURL(url);
            //linkPdfExport.NavigateUri = new Uri(url);

            //linkPdfExport.TargetName = Guid.NewGuid().ToString();
  
        }

        private void linkExcelExport_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            if (_AuslastungListViewList != null && _AuslastungListViewList.Count > 0)
            {
                List<string> lHeaderCaptions = new List<string>();
                List<List<string>> lContent = new List<List<string>>();

                lHeaderCaptions.Add("Mitarbeiter/in");
                lHeaderCaptions.Add("Nr.");
                lHeaderCaptions.Add("Klient/in");
                lHeaderCaptions.Add("FLS");
                lHeaderCaptions.Add("Beginn");
                lHeaderCaptions.Add("Ende");
                lHeaderCaptions.Add("Geleistete FLS");


                foreach (var item in _AuslastungListViewList)
                {
                    List<AuslastungRow> rows = item.AuslastungRows;

                    foreach (AuslastungRow row in rows)
                    {
                        bool addRoot = true;

                        foreach (AuslastungDetailRow detailRow in row.DetailRows)
                        {

                            if (detailRow.RowType != AuslastungRowTypes.Header)
                            {
                                List<string> content = new List<string>();
                                if (addRoot)
                                {
                                    content.Add(row.AuslastungAnalysisEmployee.DisplayName);
                                }
                                else
                                {
                                    content.Add("");
                                }
                                addRoot = false;

                                if (detailRow.RowType == AuslastungRowTypes.Total)
                                    content.Add("");
                                else 
                                    content.Add(String.Format("{0}", detailRow.Number));
                                content.Add(detailRow.CustomerName);
                                content.Add(String.Format("{0:0.##}", detailRow.ApprovedFLS));
                                content.Add(String.Format("{0:dd.MM.yyyy}", detailRow.StartDate));
                                content.Add(String.Format("{0:dd.MM.yyyy}", detailRow.EndDate));
                                content.Add(String.Format("{0:0.##}", detailRow.FLS));
                                
                                lContent.Add(content);
                            }
                        }
                    }

                }

				var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Auslastung.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.PrepareExcelFile(DownloadLinkEngine.ExcelFileId,lHeaderCaptions, lContent), sf.FileName));

                //string navitageUri = ((Hyperlink)sender).NavigateUri.ToString();
                //BeWoUtils.NavigateToReportUri(navitageUri);

                //System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
                //Workaround Hyperlink mit neuem ersetzen, Navigate Uri lässt auf dem alten nicht ändern...
                //textblock_link.Inlines.Clear();
                //var lNewLink = new Hyperlink(new Run("Excel Export"))
                //{
                //    NavigateUri = DownloadLinkEngine.GenerateNewExcelLink(),
                //    Foreground = Brushes.Black,
                //    TargetName = "newWindow"
                //};
                //lNewLink.RequestNavigate += linkExcelExport_RequestNavigate;
                //textblock_link.Inlines.Add(lNewLink);
            }
        }

        //private void RadioButton_Checked(object sender, RoutedEventArgs e)
        //{
        //    ChangeReportType();
        //}

        //private void ChangeReportType()
        //{
        //    if (reportContent != null)
        //    {
        //        reportContent.Children.Clear();
        //        _FLSOverview = null;

        //        String key = "EmployeeContentBrush";

        //        bool enabled = true;


        //        if (radioClientReport.IsChecked.Value)
        //        {
        //            key = "CustomerContentBrush";

        //            checkbox_sortBySubGroup.Content = "Nach Mitarbeiter sortieren";


        //        }
        //        else if (radioCostbearerReport.IsChecked.Value)
        //        {
        //            key = "OrganisationContentBrush";
        //            enabled = false;

        //            checkbox_sortBySubGroup.Content = "Nach Kostenträger sortieren";
        //        }
        //        else
        //        {
        //            checkbox_sortBySubGroup.Content = "Nach Klienten sortieren";
        //        }

        //        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_EmployeeOverviewAll_View))
        //        {
        //            popupedit_employee.IsEnabled = false;
        //            checkbox_all.IsEnabled = false;
        //        }
        //        else
        //        {
        //            popupedit_employee.IsEnabled = enabled;
        //            checkbox_all.IsEnabled = enabled;
        //        }
                
        //        checkbox_all_client.IsEnabled = enabled;
        //        popupedit_client.IsEnabled = enabled;
        //        lblClient.IsEnabled = enabled;
        //        lblEmployee.IsEnabled = enabled;


        //        Brush brush = BeWoApp.Current.FindResource(key) as Brush;

        //        if (brush != null)
        //            reportContent.Background = brush;
        //    }

        //}

        private void Popupedit_team_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // TeamView
            if (_SelectedTeam != null && BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e))
                CreateModalViewWindow(_SelectedTeam);
        }

        private void Popupedit_employee_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // EmployeeView
            if (_SelectedEmployee != null && BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e))
                CreateModalViewWindow(_SelectedEmployee);
        }

        private void CreateModalViewWindow<T>(T pDC) where T : IDataContract
        {
            var pDCType = pDC.GetType();

            if (pDCType == typeof (CompactEmployeeDC))
                VMFactory.CreateEmployeeVMAsync((pDC as CompactEmployeeDC).EmployeeOid,
                    cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, AuslastungReportView>(cb, this, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews((pDC as CompactEmployeeDC))))));

            if (pDCType == typeof (CompactTeamDC))
                VMFactory.CreateTeamVMAsync((pDC as CompactTeamDC).TeamOid,
                    cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<TeamVM, TeamDC, AuslastungReportView>(cb, this, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews((pDC as CompactTeamDC))))));
        }
    }
}
