package common

import (
	"fmt"
	"regexp"
	"strings"
)

var (
	// Regexp to locate relative URLs in HTML code.
	reRelativeLink = regexp.MustCompile(` (src|href|poster)=(['"])/([^'"]+)['"]`)

	// Regexp to detect common URL schemes.
	reURLScheme = regexp.MustCompile(`^https?://`)
)

// ReplaceRelativeLinksToAbsolute searches an HTML snippet for relative links
// and replaces them with absolute ones using the given base URL.
func ReplaceRelativeLinksToAbsolute(baseURL string, html string) string {
	if baseURL == "" {
		return html
	}

	matches := reRelativeLink.FindAllStringSubmatch(html, -1)
	for _, match := range matches {
		var (
			attr    = match[1]
			quote   = match[2]
			uri     = match[3]
			absURI  = strings.TrimSuffix(baseURL, "/") + "/" + uri
			replace = fmt.Sprintf(" %s%s%s%s",
				attr, quote, absURI, quote,
			)
		)
		html = strings.Replace(html, match[0], replace, 1)
	}

	return html
}

// ToAbsoluteURL converts a URL to an absolute one. If the URL is already
// absolute, it is returned as-is.
func ToAbsoluteURL(uri string, baseURL string) string {
	match := reURLScheme.FindStringSubmatch(uri)
	if len(match) > 0 {
		return uri
	}

	if strings.HasPrefix(uri, "/") {
		return strings.TrimSuffix(baseURL, "/") + uri
	}
	return strings.TrimSuffix(baseURL, "/") + "/" + uri
}
