using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using RazorLight;
using System.IO;
using System.Net;
using System.Threading.Tasks;

//https://github.com/mailgun/transactional-email-templates
//https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout
//https://github.com/toddams/RazorLight

namespace Knoks.Framework.Content
{
    public class ContentGenerator : IContentGenerator
    {
        private readonly ILogger<IContentGenerator> _logger;
        private readonly IRazorLightEngine _engine;

        public ContentGenerator(ILogger<IContentGenerator> logger)
        {
            _logger = logger;
            //_engine = EngineFactory.CreatePhysical(Path.Combine(Directory.GetCurrentDirectory(), "Templates"));
            //_engine = new EngineFactory().ForFileSystem(Path.Combine(Directory.GetCurrentDirectory(), "Templates"));
            _engine = new RazorLightEngineBuilder()
              .UseFilesystemProject(Path.Combine(Directory.GetCurrentDirectory(), "Templates"))
              .UseMemoryCachingProvider()
              .Build();
        }

        public ContentResult GenerateContent(ContentSettings contentSettings)
        {
            dynamic dataModel = contentSettings.Data;

            var contentJson = _engine.CompileRenderAsync(Path.Combine(contentSettings.Category, $"{contentSettings.Group}{contentSettings.ContentGroup}.{ContentSettings.DefaultLanguageCode}.json"), dataModel as object).Result;

            JObject defaultContent, localizedContent;
            defaultContent = localizedContent = JObject.Parse(contentJson);

            if (contentSettings.LanguageCode != ContentSettings.DefaultLanguageCode)
            {
                contentJson = _engine.CompileRenderAsync(Path.Combine(contentSettings.Category, $"{contentSettings.Group}{contentSettings.ContentGroup}.{contentSettings.LanguageCode}.json"), dataModel as object).Result;
                localizedContent = JObject.Parse(contentJson);
            }

            var model = new ContentModel(contentSettings, defaultContent, localizedContent);
            var content = _engine.CompileRenderAsync(Path.Combine(contentSettings.Category, $"{contentSettings.Group}.cshtml"), model).Result;

            //TODO: HtmlDecode fix
            content = WebUtility.HtmlDecode(content);

            return new ContentResult(model, content);
        }
    }
}
