using aeqw89.DataKeys;
using Beam.Abstractions;
using Beam.Models;
using HtmlAgilityPack;

namespace Beam.Dynamic;

public static class CommonTransformers {
    public static AsyncTransformer<HtmlDocument, ArticleData> ArticleDataTransformer(DataBindings? binding) =>
        (x) => {
            return Task.FromResult(new ArticleData() {
                Authors = binding?.Authors?.Get(x)?.Select(StringCleaner.Clean)?.ToArray() ?? [],
                Name = StringCleaner.Clean(binding?.Title?.Get(x) ?? ""),
                Categories = binding?.Tags?.Get(x)?.Select(StringCleaner.Clean)?.ToArray() ?? [],
                Description = StringCleaner.Clean(binding?.Description?.Get(x) ?? "")
            });
        };

    public static AsyncTransformer<HtmlDocument, TableOfContentsData>
        TableOfContentsTransformer(DataBindings? binding) => (x) => {
        return Task.FromResult(new TableOfContentsData() {
            Authors = binding?.Authors?.Get(x)?.Select(StringCleaner.Clean)?.ToArray() ?? [],
            Name = StringCleaner.Clean(binding?.Title?.Get(x) ?? ""),
            Categories = binding?.Tags?.Get(x)?.Select(StringCleaner.Clean)?.ToArray() ?? [],
            Description = StringCleaner.Clean(binding?.Description?.Get(x) ?? ""),
            ContentLinks = binding?.TableOfContents?.Get(x) ?? [],
            PagesLinks = binding?.PagesDropDown?.Get(x) ?? []
        });
    };

    public static AsyncTransformer<HtmlDocument, StringDocument> DocumentTransformer(DataBindings? binding,
        IDocumentMetaData? metaData = null) => (x) => {
        var resolved = binding?.Resolve(x);
        var articleData = new ArticleData() {
            Name = StringCleaner.Clean(resolved?.Title),
        };
        Dictionary<DataKey<IDocumentMetaData>, IDocumentMetaData> meta = [];
        meta.Add(IArchitecture.Default.ChapterKey, articleData);
        if (metaData is not null)
            meta.Add(IArchitecture.Default.BookKey, metaData);
        return Task.FromResult(new StringDocument(Path.GetRandomFileName(), StringCleaner.Clean(resolved?.Content)) {
            MetaData = meta
        });
    };
}