using System.Text;
using Beam.Abstractions;
using Beam.Models;

namespace Beam.Exports {
    public class HtmlExporter : PlainTextExporter {
        public HtmlExporter(IDocument document,
                               ArticleData? meta = null,
                               Dictionary<string, string>? linkButtons = null,
                               string? eofHtml = null) : base(document) {
            Meta = meta;
            LinkButtons = linkButtons;
            EofHtml = eofHtml;
        }

        public ArticleData? Meta { get; }
        public Dictionary<string, string>? LinkButtons { get; }
        public string? EofHtml { get; }

        protected override string Convert() {
            var text = Document.ToString();
            // Convert newlines to <p></p> tags
            text = "<p>" + text.Replace("\n", "</p><p>") + "</p>";
            if (Meta is null)
                return text;
            text = $"<h1>{Meta.Name}</h1>" + text;
            if (LinkButtons is null || LinkButtons.Count == 0)
                return text;
            StringBuilder buttons = new();
            foreach(var (btnText, btnLink) in LinkButtons.Select((x) => (x.Key, x.Value))) {
                buttons.AppendLine($"<a href=\"{btnLink}\">{btnText}</a>");
            }
            var buttonsDiv = $"<div class=\"controls\">{buttons}</div>";
            text = buttonsDiv + text + buttonsDiv;
            text += EofHtml ?? "";
            text = "<!DOCTYPE html>\n<html>" + text + "</html>";
            return text;
        }

        protected override Task<string> ConvertAsync() {
            return Task.FromResult(Convert());
        }
    }
}
