#if DEBUG
//#define CREATE_PREVIEW_HTML
#endif
using iText.Html2pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WK5.Core.Models;
using WK5.Core.Models.Inventuren;
using WK5.Core.Services;

namespace WK5.Core.Drucken.InventurRegalErfassungen
{
    public class PrintInventurRegalErfassung : PrintBase
    {
        private readonly Inventur _inventur;
        private readonly string _hauptlager;
        private readonly InventurService _inventurService;
        private readonly List<Personal> _personal;

        private PrintInventurRegalErfassung(Inventur inventur, string hauptlager, InventurService inventurService, List<Personal> personal)
        {
            _layoutFile = "InventurRegalErfassung.html";
            _template = String.Empty;
            _inventur = inventur;
            _hauptlager = hauptlager;
            _inventurService = inventurService;
            _personal = personal;
        }
        public static async Task<PrintInventurRegalErfassung> CreateAsync(Inventur inventur, string hauptlager, InventurService inventurService, List<Personal> personal)
        {
            var myClass = new PrintInventurRegalErfassung(inventur, hauptlager, inventurService, personal);
            await myClass.InitializeAsync();
            return myClass;
        }
        public override string Print(string speicherpfad)
        {
            string filename = $"INVENTUR_{_inventur.Jahr}_{_inventur.InventurId}_{_hauptlager}.pdf";
#if CREATE_PREVIEW_HTML
            File.WriteAllText(Path.Combine(speicherpfad, $"INVENTUR_{_inventur.Jahr}_{_inventur.InventurId}_{_hauptlager}.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()
        {
            StringBuilder tableBuilder = new StringBuilder();

            List<int> userIds = new List<int>();
            using FbController2 fbController = new FbController2();
            ArtikelService artikelService = new ArtikelService();
            await foreach (var unterlager in _inventurService.GetUnterlagerAsync(_inventur.InventurId, _hauptlager))
            {
                await foreach (var buchung in _inventurService.GetGebuchteArtikelByUnterlagerAsync(_inventur.InventurId, unterlager.Lagerplatz))
                {
                    Artikel? artikel = await artikelService.GetAsync(buchung.Artikelnummer, fbController);
                    if (!userIds.Contains(buchung.UserId))
                    {
                        userIds.Add(buchung.UserId);
                    }
                    string bezeichnung = artikel is null ? "Unbekannt" : $"{artikel.Bezeichnung1} {artikel.Bezeichnung2}".Trim();
                    tableBuilder.AppendLine("<tr>");
                    tableBuilder.AppendLine($"\t<td class=\"nowrap\">{buchung.Artikelnummer}</td>");
                    tableBuilder.AppendLine($"\t<td class=\"position-bezeichnung \">{bezeichnung}</td>");
                    tableBuilder.AppendLine($"\t<td class=\"nowrap\">{buchung.Regal}</td>");
                    tableBuilder.AppendLine($"\t<td class=\"nowrap\">{buchung.Menge}</td>");
                    tableBuilder.AppendLine("</tr>");
                }
            }

            var mitarbeiterNamen = String.Join(", ", _personal.Where(x => userIds.Contains(x.PERS_N_NR)).Select(x => x.PERS_A_NAME));

            _template = _template
                .Replace("{{ DISPLAY_CSS }}", GenerateDisplayCss())
                .Replace("{{ REGAL }}", _hauptlager)
                .Replace("{{ JAHR }}", _inventur.Jahr.ToString())
                .Replace("{{ BUCHUNGEN }}", tableBuilder.ToString())
                .Replace("{{ MITARBEITER }}", mitarbeiterNamen)
                .Replace("{{ DRUCKDATUM }}", DateTime.Now.ToShortDateString())
                .Replace("{{ UNTERSCHRIFT_DESCRIPTION }}", _hauptlager.Equals("KORREKTUR", StringComparison.OrdinalIgnoreCase) ? "Datum, Unterschriften aller Mitarbeiter" : "Inventurerfasser: Datum, Unterschrift")
                ;

            return _template;
        }
    }
}
