using CefSharpWrap;
using CefSharpWrap.CustomResource;
using System;
using System.IO;
using System.Reflection;

namespace MarkdownRenderer
{

    public static class MarkdownRendererMain
    {
        internal static readonly string CustomResourcePath = $"{nameof(MarkdownRenderer)}-{Guid.NewGuid()}";

        static MarkdownRendererMain()
        {
            InitReferenceAssembly();
        }

        private static void InitReferenceAssembly()
        {
            CefSharpWrapFactory.AddCustomResource($"/{CustomResourcePath}/", "text/html"
#if DEBUG
                , new FileByteProvider(Path.Combine(MarkdownRendererDebugSupport.MrResourceDir, "TemplatePage.html"))
#else
                , new BytesProvider(System.Text.Encoding.UTF8.GetBytes(Properties.Resources.TemplatePage))
#endif
                );
        }

#if DEBUG

        private class FileByteProvider : IBytesProvider
        {
            private readonly string _path;

            public FileByteProvider(string path) => _path = path;

            public int Length => (int)new FileInfo(_path).Length;

            public byte[] GetBytes() => File.ReadAllBytes(_path);
        }

#endif
        internal static IConfigStore ConfigStore { get; private set; }

        public static void Init(IConfigStore configStore = null)
        {
            //ensure static ctor fire and
            ConfigStore = configStore;
        }

        public static void Quit()
        {
            ConfigStore?.Flush();
            CefSharpWrapFactory.Shutdown();
        }
    }
}