using bdHerramientaCACOA.dbcontext;
using BlazorBootstrap;
using DinkToPdf;
using DinkToPdf.Contracts;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Text;
namespace HerramientaCASA
{
    public class ServicioPDF
    {
        private readonly IConverter _converter;
        private readonly IWebHostEnvironment _env;

        public ServicioPDF(IConverter converter, IWebHostEnvironment env)
        {
            _converter = converter;
            _env = env;
        }

        public byte[] GenerarPdf(string html)
        {
            try
            {
                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings = {
                    PaperSize = PaperKind.A4,
                    Orientation = DinkToPdf.Orientation.Portrait,
                    Margins= new MarginSettings
                    {
                        Top = 11.8,
                        Left = 0,
                        Right = 0,
                        Bottom = 10
                    },
                },
                    Objects = {
                new ObjectSettings() {
                     HtmlContent = html,
                     HeaderSettings = new HeaderSettings
                     {
                         //HtmUrl = Path.Combine(Environment.CurrentDirectory, "wwwroot", "Imprimir", "HeaderImprimir.html")
                         //HtmUrl = "https://localhost:7275/HeaderPdf"
                         HtmUrl = obtenerURL()
                     },
                }
            }
                };

                return _converter.Convert(doc);
            }
            catch (Exception ex)
            {
                    throw new Exception(ex.Message);
            }
        }

        public string obtenerURL()
        {
            string url = "";
            var bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: false);

            if (_env.IsDevelopment())
            {
                url = "https://localhost:7275/HeaderPdf";
            }
            else
            {
                url = bd.enumeraciones.First(x => x.Codigo.Contains("CW.DOMINIO")).ValorAlfabetico1 + "/HeaderPdf";
            }

            return url;
        }
    }
}