using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Navigation;
using BS.Shared;
using BS.Shared.DataContracts.Reports;
using BeWo.Core;
using BeWo.ServiceProxy;
using BS.Shared.Extensions;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Grid;
using Microsoft.Win32;

namespace BeWo.View.Detail.Report
{
    /// <summary>
    /// Interaction logic for QueryView.xaml
    /// </summary>
    public partial class AccountingReportView : BeWoView
    {
        private DateTime _StartDate = new DateTime(2012,9,1);
        private DateTime _EndDate = DateTime.Now;

        public AccountingReportView()
        {
            InitializeComponent();

            try
            {
                datePickerStartDate.DateTime = _StartDate;
                datePickerEndDate.DateTime = _EndDate;

                textblock_link.Visibility = Visibility.Collapsed;
                textblock_link_pdfexport.Visibility = Visibility.Collapsed;

                DownloadLinkEngine = new DownloadLinkEngine();
                linkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();

                btnExecuteQuery.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public DownloadLinkEngine DownloadLinkEngine { get; set; }

        public override string Title
        {
            get { return "öffentliche Abfragen"; } 
        }

        private void linkExcelExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var lView = this.datagrid_result.View as TableView;

            List<string> lHeaderCaptions = new List<string>();
            List<List<string>> lContent = new List<List<string>>();

            if (lView != null)
            {
                foreach (var iCol in lView.VisibleColumns)
                {
                    lHeaderCaptions.Add(iCol.HeaderCaption.ToString());

                    for (int iRowIndex = 0; iRowIndex < this.datagrid_result.VisibleRowCount; iRowIndex++)
                    {
                        if (lContent.Count <= iRowIndex)
                        {
                            lContent.Add(new List<string>());
                        }

                        lContent[iRowIndex].Add(this.datagrid_result.GetCellValue(iRowIndex, iCol).ToStringNullCheck());
                    }
                }
            }

            var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Abrechnung.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));
            //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...
            //this.textblock_link.Inlines.Clear();
            //var lNewLink = new Hyperlink(new Run("Excel Export")) { NavigateUri = this.DownloadLinkEngine.GenerateNewExcelLink(), Foreground = Brushes.Black, TargetName = "newWindow" };
            //lNewLink.RequestNavigate += this.linkExcelExport_RequestNavigate;
            //this.textblock_link.Inlines.Add(lNewLink);
        }

        private void linkPdfExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
            //QueryDC lQuery = this.combo_query.SelectedItem as QueryDC;
            //if (lQuery != null)
            //{
            //    DataTable dt = this.datagrid_result.DataSource as DataTable;
            //    ServiceFacade.DoQueryServiceSync(q => q.PrepareQueryReport(dt, BeWoApp.Tenant + "queryeoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid));
            //}
        }

        private void linkPdfExport_direct_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
            //QueryDC lQuery = this.combo_query.SelectedItem as QueryDC;
            //if (lQuery != null)
            //{
            //    List<QueryParamDC> parameterList = this.CreateQueryParamValues(lQuery);

            //    DataTable dt = ServiceFacade.DoQueryServiceSync(s => s.ExecuteQuery(lQuery.Oid, parameterList));
            //    ServiceFacade.DoQueryServiceSync(q => q.PrepareQueryReport(dt, BeWoApp.Tenant + "queryeoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid));
            //}
        }

        private void btnExecuteQuery_Click(object sender, RoutedEventArgs e)
        {
            textblock_link.Visibility = Visibility.Visible;
            textblock_link_pdfexport.Visibility = Visibility.Visible;

            datagrid_result.Visibility = Visibility.Visible;
            datagrid_result.Columns.Clear();

            ShowSupportConcepts();
        }

        private void ShowSupportConcepts()
        {
            ServiceFacade.DoAnalysisServiceAsync<AccountingReportDC>(
                s =>
                {
                    try
                    {
                        return s.CreateAccountingReport(_StartDate, _EndDate);
                    }
                    catch (Exception) {}

                    return null;
                },
                r => this.Dispatch(delegate
                {
                    DataTable x = ConvertAccountingReportDCToDataTable(r);
                    datagrid_result.ItemsSource = x;
                }));
        }

        private DataTable ConvertAccountingReportDCToDataTable(AccountingReportDC accountingReportDC)
        {
            var table = new DataTable();

            table.Columns.Add("Name");
            table.Columns.Add("Hilfeplan");
            table.Columns.Add("Kostenträger");
            table.Columns.Add("FLS");
            table.Columns.Add("Stundensatz");
            table.Columns.Add("Pauschaler Faktor");
            table.Columns.Add("Forderung");

            var col = table.Columns;
            col["FLS"].DataType = typeof(decimal);
            col["Stundensatz"].DataType = typeof(decimal);
            col["Pauschaler Faktor"].DataType = typeof(decimal);
            col["Forderung"].DataType = typeof(decimal);

            foreach(var rowDC in accountingReportDC.AccountingReportRows)
            {
                var row = table.NewRow();
                
                decimal hourlyRate = 0;
                decimal factor = 0;

                var crp =
                    rowDC.CostBearer.Organisation.CostRatePeriods.GetCostRatePeriodForDate(
                        CostRatePeriodType.HourlyRate, _StartDate);
                
                if (crp != null && crp.CostRateValue.HasValue)
                    hourlyRate = crp.CostRateValue.Value;

                crp =
                    rowDC.CostBearer.Organisation.CostRatePeriods.GetCostRatePeriodForDate(
                        CostRatePeriodType.RateFactor, _StartDate);
                
                if (crp != null && crp.CostRateValue.HasValue)
                    factor = crp.CostRateValue.Value;

                decimal amount = (((rowDC.TotalDuration/60)*hourlyRate)*(100 + factor))/100;

                row["Name"] = rowDC.Customer;
                row["Hilfeplan"] = string.Format("{0:d}", rowDC.SupportConceptStart) + " - " + string.Format("{0:d}", rowDC.SupportConceptEnd);
                row["Kostenträger"] = rowDC.CostBearer.OrganisationName;
                row["FLS"] = Math.Round((rowDC.TotalDuration / 60), 2);
                row["Stundensatz"] = Math.Round((hourlyRate), 2);
                row["Pauschaler Faktor"] = Math.Round((factor), 2);
                row["Forderung"] = Math.Round((amount), 2);

                table.Rows.Add(row);
            }

            return table;
        }

        private void datePickerStartDate_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            var dp = (DateEdit)sender;
            _StartDate = dp.DateTime;
            if(datagrid_result.Visibility.Equals(Visibility.Visible))
                ShowSupportConcepts();
        }

        private void datePickerEndDate_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            var dp = (DateEdit)sender;
            _EndDate = dp.DateTime;
            if (datagrid_result.Visibility.Equals(Visibility.Visible))
                ShowSupportConcepts();
        }
    }
}