package main

// 递归，函数可以直接或间接的调用自身。
// 对许多问题而言，递归是一种强有力的技术，
// 例如处理递归的数据结构。

import (
	"fmt"
	"os"

	"golang.org/x/net/html"
)

func main() {
	doc, err := html.Parse(os.Stdin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)
		os.Exit(1)
	}
	//fmt.Println(doc.NextSibling.Data)
	for _, link := range Visit(nil, doc.FirstChild) {
		fmt.Println(link)
	}
	//outline(nil, doc)
}

// visit appends to links each link found in n and returns the result.
func Visit(links []string, n *html.Node) []string {
	if n == nil {
		return links
	}
	if n.Type == html.ElementNode && n.Data == "a" {
		for _, a := range n.Attr {
			if a.Key == "href" {
				links = append(links, a.Val)
				//fmt.Println(a.Val)
			}
		}
	}
	//for c := n.FirstChild; c != nil; c = c.NextSibling {
	//	links = visit(links, c)
	//}
	//if n != nil {
	//	links = visit(links, n.NextSibling)
	//}
	links = Visit(links, n.FirstChild)
	links = Visit(links, n.NextSibling)
	return links
}
func outline(stack []string, n *html.Node) []string {
	if n.Type == html.ElementNode {
		stack = append(stack, n.Data)
		fmt.Println(stack)
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		outline(stack, c)
	}
	return stack
}
