using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Beam.Abstractions;

namespace Beam.Dynamic {
    public class AnchorCollectionDataProvider : IComposableDataProvider<string[]> {
        public IBinding? Content { get; set; }
        public Uri? RelativeTo { get; set; }

        public string[] Get(HtmlDocument document) {
            var node = Select(document);
            return node is null ? [] : Get(node);      
        }

        public string[] Get(HtmlNode node) {
            List<string> links = [];
            foreach (var child in node.Descendants()) {
                var href = child.GetAttributeValue("href", "");
                if (Uri.TryCreate(RelativeTo, href, out var uri))
                    links.Add(uri.AbsoluteUri);
            }

            return links.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
        }
        
        public HtmlNode? Select(HtmlDocument doc) {
            return Content?.Select(doc);       
        }

        public HtmlNode? Select(HtmlNode node) {
            return node;
        }


        public HtmlNode[]? SelectMany(HtmlDocument doc) {
            throw new NotImplementedException();
        }
        public HtmlNode[]? SelectMany(HtmlNode[] node) {
            throw new NotImplementedException();
        }
    }
}
