// Copyright © Selmo Technology GmbH. All Rights Reserved

using Markdig;
using Markdig.Renderers;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using Microsoft.JSInterop;
using SelmoStudio.Hmi.Server.SelmoHmi.Helpers;
using SelmoStudio.Hmi.Server.Shared.Resources;

namespace SelmoStudio.Hmi.Server.Shared.Components.BaseComponents
{
    public partial class MarkdownViewerComponent : ComponentBase
    {
        private string _markdownContent;
        private string _renderedContent;
        private string _errorMessage;
        private MarkdownPipeline _pipeline;
        private StringWriter _writer;
        private HtmlRenderer _renderer;

        [Inject]
        private IStringLocalizer<HmiResource> _localizer { get; set; }

        [Inject]
        private IJSRuntime _js { get; set; }

        [Parameter]
        public string FilePath { get; set; }

        protected override async Task OnParametersSetAsync()
        {
            _pipeline = new MarkdownPipelineBuilder()
                .UseAdvancedExtensions()
                .UseEmojiAndSmiley()
                .UseGridTables()
                .UseBootstrap()
                .Build();

            _writer = new StringWriter();
            _renderer = new HtmlRenderer(_writer);
            _pipeline.Setup(_renderer);

            await LoadMarkdownContent();
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await _js.InvokeVoidAsync("Prism.highlightAll");
            }
        }

        private async Task LoadMarkdownContent()
        {
            try
            {
                if (string.IsNullOrEmpty(FilePath))
                {
                    _errorMessage = @_localizer[nameof(HmiResource.MarkdownViewerErrorFilePathNotProvided)];
                    return;
                }

                _markdownContent = await File.ReadAllTextAsync(FilePath);

                var document = Markdown.Parse(_markdownContent, _pipeline);
                _renderer.ObjectRenderers.AddIfNotAlready(new CodeBlockRenderer());

                _renderer.Render(document);
                _renderedContent = _writer.ToString();

                _renderedContent = Markdown.ToHtml(_markdownContent, _pipeline);
            }
            catch (Exception)
            {
                _errorMessage = @_localizer[nameof(HmiResource.MarkdownViewerErrorLoadingFile)];
            }
        }
    }
}