#define CREATE_PREVIEW_HTML
using iText.Html2pdf;
using KarleyLibrary.Erweiterungen;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WK5.Core.Basis.Erweiterungen;
using WK5.Core.Basis.Filter;
using WK5.Core.Models;

namespace WK5.Core.Drucken.ProvisionsAbrechnung
{
    public class PrintProvisionsAbrechnung : PrintBase
    {
        private readonly List<Provision> _provisionen;
        private readonly Vertreter _vertreter;
        private readonly Zeitraum _zeitraum;

        private PrintProvisionsAbrechnung(List<Provision> provisionen, Vertreter vertreter, Zeitraum zeitraum)
        {
            _layoutFile = "ProvisionsAbrechnung.html";
            _template = String.Empty;
            _provisionen = provisionen;
            _vertreter = vertreter;
            _zeitraum = zeitraum;
        }
        public static async Task<PrintProvisionsAbrechnung> CreateAsync(List<Provision> provisionen, Vertreter vertreter, Zeitraum zeitraum)
        {
            var myClass = new PrintProvisionsAbrechnung(provisionen, vertreter, zeitraum);
            await myClass.InitializeAsync();
            return myClass;
        }
        public override string Print(string speicherpfad)
        {
            string filename = $"PV_{_zeitraum.Von:yyyy_MM_dd}_{_vertreter.VERT_N_NR}.pdf";

#if CREATE_PREVIEW_HTML
            File.WriteAllText(Path.Combine(speicherpfad, $"PV_{_zeitraum.Von:yyyy_MM_dd}_{_vertreter.VERT_N_NR}"), _template);
#endif
            byte[] byteArray = Encoding.UTF8.GetBytes(_template);
            MemoryStream stream = new MemoryStream(byteArray);
            ConverterProperties converterProperties = new ConverterProperties()
                .SetBaseUri(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LAYOUT_PATH));

            string fullPath = Path.Combine(speicherpfad, filename);
            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
            }

            HtmlConverter.ConvertToPdf(stream, new FileStream(fullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None), converterProperties);

            return fullPath;
        }

        protected override string GenerateDisplayCss()
        {
            return string.Empty;
        }

        protected override async Task InitializeAsync()
        {
            string layoutPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LAYOUT_PATH, _layoutFile);
            _template = await File.ReadAllTextAsync(layoutPath);
            SetRegeln();
            _template = await SetTemplateVariables();
        }

        protected override Task InitializeAsync(FbController2 fbController)
        {
            throw new NotImplementedException();
        }

        protected override void SetRegeln()
        {

        }

        protected override async Task<string> SetTemplateVariables()
        {

            StringBuilder provisionsBuilder = new StringBuilder();
            decimal gesamtProvision = 0;
            foreach (var provision in _provisionen)
            {
                provisionsBuilder.AppendLine("<tr>");
                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision.Belegtyp}-{provision.Belegnummer}");
                provisionsBuilder.AppendLine("\t</td>");

                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision.Belegdatum.ToShortDateString()}");
                provisionsBuilder.AppendLine("\t</td>");

                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision.Kundenname}");
                provisionsBuilder.AppendLine("\t</td>");

                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision.Netto:0.00}");
                provisionsBuilder.AppendLine("\t</td>");

                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision.PosNummer}");
                provisionsBuilder.AppendLine("\t</td>");

                decimal provision_summe = provision.Netto * provision.ProvisionsSatz / 100;
                gesamtProvision += provision_summe;
                provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
                provisionsBuilder.AppendLine($"\t\t{provision_summe:0.00}");
                provisionsBuilder.AppendLine("\t</td>");

                provisionsBuilder.AppendLine("</tr>");
            }

            provisionsBuilder.AppendLine("<tr>");
            provisionsBuilder.AppendLine("\t<td class=\"font-weight-bold text-right\" colspan=\"5\">");
            provisionsBuilder.AppendLine($"\t\tGesamt:");
            provisionsBuilder.AppendLine("\t</td>");
            provisionsBuilder.AppendLine("\t<td class=\"text-right\">");
            provisionsBuilder.AppendLine($"\t\t{gesamtProvision:0.00}");
            provisionsBuilder.AppendLine("\t</td>");
            provisionsBuilder.AppendLine("</tr>");


            decimal provision_satz = _provisionen.FirstOrDefault()?.ProvisionsSatz ?? _vertreter.VERT_N_PROVISION;

            _template = _template
                .Replace("{{ DISPLAY_CSS }}", GenerateDisplayCss())
                .Replace("{{ IMPRESSUM }}", GlobalConfig.Configuration.FirmenDaten.ImpressumHtmlDruckformulare())
                .Replace("{{ ABS_FIRMA }}", GlobalConfig.Configuration.FirmenDaten.Firmenname)
                .Replace("{{ ABS_STRASSE }}", GlobalConfig.Configuration.FirmenDaten.Firmenanschrift.Strasse)
                .Replace("{{ ABS_LAND }}", GlobalConfig.Configuration.FirmenDaten.Firmenanschrift.Land)
                .Replace("{{ ABS_PLZ }}", GlobalConfig.Configuration.FirmenDaten.Firmenanschrift.Postleitzahl)
                .Replace("{{ ABS_ORT }}", GlobalConfig.Configuration.FirmenDaten.Firmenanschrift.Ort)
                .Replace("{{ PROVSIONSNUMMER }}", _zeitraum.Von.ToString("M/yyyy", CultureInfo.InvariantCulture))
                .Replace("{{ ADDRESSZEILE1 }}", _vertreter.GetName())
                .Replace("{{ VERTRETER_NR }}", _vertreter.VERT_N_NR.ToString())
                .Replace("{{ PROVISION_PROZENT }}", provision_satz.ToString("0.00"))
                .Replace("{{ ZEITRAUM }}", $"{_zeitraum.Von.ToShortDateString()} - {_zeitraum.Bis.ToShortDateString()}")
                .Replace("{{ ADDRESSZEILE2 }}", string.Empty)
                .Replace("{{ ADDRESSZEILE3 }}", string.Empty)
                .Replace("{{ ADDRESSZEILE4 }}", string.Empty)
                .Replace("{{ EMP_STRASSE }}", string.Empty)
                .Replace("{{ EMP_LAND }}", string.Empty)
                .Replace("{{ EMP_PLZ }}", string.Empty)
                .Replace("{{ EMP_ORT }}", string.Empty)
                .Replace("{{ DATUM }}", DateTime.Now.ToShortDateString())
                .Replace("{{ PROVISIONEN }}", provisionsBuilder.ToString())
                ;

            return await Task.FromResult(_template);
        }
    }
}
