package htmlutil

import (
	"golang.org/x/net/html"
	"strings"
)

func AppendHtmlAsChilds(parent *html.Node, htmlFragment string) error {
	children, err := html.ParseFragment(strings.NewReader(htmlFragment), parent)
	if err != nil {
		return err
	}
	for _, c := range children {
		parent.AppendChild(c)
	}
	return nil
}

func RemoveAllChildren(n *html.Node) {
	children := make([]*html.Node, 0)
	for c := range n.ChildNodes() {
		children = append(children, c)
	}
	for _, c := range children {
		n.RemoveChild(c)
	}
}

func FilterNodes(root *html.Node, filter func (*html.Node) bool, resultMaxLen int) []*html.Node {
	result := make([]*html.Node, 0)
	for node := range root.Descendants()  {
		if len(result) >= resultMaxLen {
			return result
		} else if filter(node) {
			result = append(result, node)
		}
	}
	return result
}

func FilterNode(root *html.Node, filter func(*html.Node) bool) *html.Node {
	var result *html.Node = nil
	for node := range root.Descendants()  {
		if filter(node) {
			return node
		}
	}
	return result
}


func FindElementWithID(root *html.Node, id string) *html.Node {
	return FilterNode(root, func(n *html.Node) bool {
		if n.Type == html.ElementNode {
			for _, attr := range n.Attr {
				if attr.Key == "id" && attr.Val == id {
					return true
				}
			}
		}
		return false
	})
}

