using HtmlAgilityPack;
using MangaReader.Core.Http;
using MangaReader.Core.Pages;

namespace MangaReader.Core.Sources.NatoManga.Pages;

public class NatoMangaPageProvider(IHtmlLoader htmlLoader) : IMangaPageProvider
{
    public string SourceId => "NatoManga";

    public async Task<IReadOnlyList<string>> GetPageImageUrlsAsync(string chapterUrl, CancellationToken cancellationToken)
    {
        List<string> imageUrlCollection = [];

        HtmlDocument document = await htmlLoader.GetHtmlDocumentAsync(chapterUrl, cancellationToken);
        HtmlNodeCollection? htmlNodeCollection = GetImageNodeCollection(document);

        if (htmlNodeCollection == null)
            return imageUrlCollection;

        foreach (var htmlNode in htmlNodeCollection)
        {
            string imageSourceUrl = htmlNode.GetAttributeValue<string>("src", string.Empty);

            if (string.IsNullOrWhiteSpace(imageSourceUrl))
                continue;

            imageUrlCollection.Add(imageSourceUrl);
        }

        return imageUrlCollection;
    }

    private static HtmlNodeCollection? GetImageNodeCollection(HtmlDocument document)
    {
        HtmlNode? chapterReaderNode = document.DocumentNode.SelectSingleNode(".//div[@class='container-chapter-reader']");

        if (chapterReaderNode == null)
            return null;

        return chapterReaderNode.SelectNodes(".//img");
    }
}