package main

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"html/template"
	mathrand "math/rand"
	"net/http"
	"strings"
	"time"
)

var (
	funcs = template.FuncMap{
		"sub": func(a, b int) int {
			return a - b
		},
		"add": func(a, b int) int {
			return a + b
		},
		"translate": Translate,
		"toJSON": func(v interface{}) (string, error) {
			jsonBytes, err := json.Marshal(v)
			if err != nil {
				return "", err
			}
			return string(jsonBytes), nil
		},
	}
)

type SearchEngine struct {
	Name string
	Func func(string, string, string, int) ([]SearchResult, time.Duration, error)
}

// Helper function to render templates without elapsed time measurement
func renderTemplate(w http.ResponseWriter, tmplName string, data map[string]interface{}) {
	// Generate icon paths for SVG and PNG, including a 1/10 chance for an alternate icon
	iconPathSVG, iconPathPNG := GetIconPath()

	// Add icon paths to data map so they are available in all templates
	if data == nil {
		data = make(map[string]interface{})
	}
	data["IconPathSVG"] = iconPathSVG
	data["IconPathPNG"] = iconPathPNG

	// Parse and execute the template with shared functions
	tmpl, err := template.New(tmplName).Funcs(funcs).ParseFiles("templates/" + tmplName)
	if err != nil {
		printErr("Error parsing template: %v", err)
		http.Error(w, Translate("internal_server_error"), http.StatusInternalServerError)
		return
	}

	// Execute the template
	err = tmpl.Execute(w, data)
	if err != nil {
		printErr("Error executing template: %v", err)
		http.Error(w, Translate("internal_server_error"), http.StatusInternalServerError)
	}
}

// Randoms string generator used for auth code
func generateStrongRandomString(length int) string {
	bytes := make([]byte, length)
	_, err := rand.Read(bytes)
	if err != nil {
		printErr("Error generating random string: %v", err)
	}
	return base64.URLEncoding.EncodeToString(bytes)[:length]
}

// Checks if the URL already includes a protocol
func hasProtocol(url string) bool {
	return strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")
}

// Checks if the domain is a local address
func isLocalAddress(domain string) bool {
	return domain == "localhost" || strings.HasPrefix(domain, "127.") || strings.HasPrefix(domain, "192.168.") || strings.HasPrefix(domain, "10.")
}

// Ensures that HTTP or HTTPS is before the address if needed
func addProtocol(domain string) string {
	if hasProtocol(domain) {
		return domain
	}
	if isLocalAddress(domain) {
		return "http://" + domain
	}
	return "https://" + domain
}

// GetIconPath returns both SVG and PNG icon paths, with a 1/10 chance for a randomly generated "alt" icon.
func GetIconPath() (string, string) {
	// 1 in 10 chance to select an alt icon
	if mathrand.Intn(10) == 0 {
		// Generate a random number between 2 and 4
		altIconNumber := 2 + mathrand.Intn(3) // mathrand.Intn(3) generates 0, 1, or 2
		selectedAltIcon := "icon-alt" + fmt.Sprint(altIconNumber)
		return "/static/images/" + selectedAltIcon + ".svg", "/static/images/" + selectedAltIcon + ".png"
	}
	// Default paths
	return "/static/images/icon.svg", "/static/images/icon.png"
}