#if DEBUG
#define CREATE_PREVIEW_HTML
#endif
using iText.Html2pdf;
using PDFtoPrinter;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using WK5.Core.Email;
using WK5.Core.Models;

namespace WK5.Core.Drucken.Erstkundenbrief
{
    public class PrintErstkundenbrief : PrintBase
    {
        private readonly Beleg _beleg;

        private PrintErstkundenbrief(Beleg beleg)
        {
            _layoutFile = "Erstkundenbrief.html";
            _template = String.Empty;
            _beleg = beleg;
        }

        public static async Task<PrintErstkundenbrief> CreateAsync(Beleg beleg)
        {
            var myClass = new PrintErstkundenbrief(beleg);
            await myClass.InitializeAsync();
            return myClass;
        }
        public override string Print(string speicherpfad)
        {
            string filename = $"ERSTKUNDENBRIEF_{_beleg.Kundennummer}.pdf";

#if CREATE_PREVIEW_HTML
            File.WriteAllText(Path.Combine(speicherpfad, $"ERSTKUNDENBRIEF_{_beleg.Kundennummer}.html"), _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.OpenOrCreate, 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()
        {
            return;
        }

        protected override async Task<string> SetTemplateVariables()
        {
            string anredeName = _beleg.Anrede.Equals("Sehr geehrte Damen und Herren", StringComparison.OrdinalIgnoreCase) ? _beleg.Anrede : $"{_beleg.Anrede} {_beleg.Ansprechpartner}";
            _template = _template
               .Replace("{{ DISPLAY_CSS }}", GenerateDisplayCss())
               .Replace("{{ ANREDE_NAME }}", $"{anredeName.Trim()},")
               ;

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