package main

import (
	"fmt"
	"net/url"
	"sort"
	"strings"
)

func RouteGoldberry(u *url.URL) (string, error) {
	switch strings.ToLower(u.Host) {
	case "home":
		return GoldberryHome()
	default:
		return ConvertErrorToHTML(90, "The requested route does not exist"), nil
	}
}

func GoldberryHome() (string, error) {
	var out strings.Builder

	out.WriteString("<h1>Home</h1>\n<hr>\n")
	out.WriteString(CustomHTML())
	out.WriteString("<h2>Most Visited</h3>\n<hr>\n")
	out.WriteString(MostVisited())
	out.WriteString(HistoryOutput())
	return out.String(), nil
}

func CustomHTML() string {
	if !settings.UseCustomHome {
		return "\n"
	}
	return settings.CustomHomeHTML
}

func MostVisited() string {
	if !settings.KeepHistory {
		return "<p>History is currently disabled</p>\n"
	}
	if len(settings.History) == 0 {
		return ""
	}

	format := `<a href="%s">%s</a><br>`

	hash := make(map[string]int)
	counts := make([]VisitedPage, 0, len(settings.History))
	for _, u := range settings.History {
		hash[u]++
	}
	for k, v := range hash {
		counts = append(counts, VisitedPage{v, k})
	}
	sort.Slice(counts, func(i, j int) bool {
		return counts[i].count > counts[j].count
	})
	countOfCounts := 5
	if len(counts) < 5 {
		countOfCounts = len(counts)
	}

	var out strings.Builder
	out.WriteString("<p>")
	for _, c := range counts[:countOfCounts] {
		out.WriteString(fmt.Sprintf(format, c.u, c.u))
	}
	out.WriteString("</p>")
	return out.String()
}

func HistoryOutput() string {
	if !settings.KeepHistory {
		return "\n"
	}
	format := "\t<a href=\"%s\">%s</a><br>\n"

	var out strings.Builder
	out.WriteString("<details>\n\t<summary>Full History</summary>\n")
	for _, u := range settings.History {
		out.WriteString(fmt.Sprintf(format, u, u))
	}
	out.WriteString("</details>\n")
	return out.String()
}
