using RazorLight;
using System;
using System.Threading.Tasks;

namespace Elwig.Helpers.Printing {
    public static class Html {

        private static RazorLightEngine? Engine = null;
        public static bool IsReady => Engine != null;

        public static async Task Init(Action? evtHandler = null) {
            var e = new RazorLightEngineBuilder()
                .UseFileSystemProject(App.DocumentsPath)
                .UseMemoryCachingProvider()
                .Build();

            await Task.Delay(500);

            await e.CompileTemplateAsync("Document");
            await e.CompileTemplateAsync("BusinessDocument");
            await e.CompileTemplateAsync("BusinessLetter");

            await e.CompileTemplateAsync("CreditNote");
            await e.CompileTemplateAsync("DeliveryAncmtList");
            await e.CompileTemplateAsync("DeliveryConfirmation");
            await e.CompileTemplateAsync("DeliveryDepreciationList");
            await e.CompileTemplateAsync("DeliveryJournal");
            await e.CompileTemplateAsync("DeliveryNote");
            await e.CompileTemplateAsync("Letterhead");
            await e.CompileTemplateAsync("MemberDataSheet");
            await e.CompileTemplateAsync("MemberList");
            await e.CompileTemplateAsync("PaymentVariantSummary");
            await e.CompileTemplateAsync("WineQualityStatistics");

            Engine = e;
            evtHandler?.Invoke();
        }

        public static async Task<string> CompileRenderAsync(string key, object model) {
            if (Engine == null) throw new InvalidOperationException("The razor engine has not been initialized yet");
            return await Engine.CompileRenderAsync(key, model);
        }
    }
}
