package web

import (
	"log"
	"music-server/pkg/server"
	"net/http"
	"regexp"
	"strings"
)

var games_added []string

func FindGameWebHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
	}

	search_term := r.FormValue("search_term")

	search(search_term)

	component := FoundGames(games_added)
	err = component.Render(r.Context(), w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		log.Fatalf("Error rendering in FindGameWebHandler: %e", err)
	}
}

func search(searchText string) {
	games_added = nil
	games := server.GetAllGames()
	for _, game := range games {
		if is_match_exact(searchText, game) {
			add_game(game)
		}
	}
	for _, game := range games {
		if is_match_contains(clean_term(searchText), clean_term(game)) {
			add_game(game)
		}
	}
	for _, game := range games {
		if is_match_regex(clean_term(searchText), clean_term(game)) {
			add_game(game)
		}
	}
}

func is_match_exact(search_term string, game_name string) bool {
	search_term = strings.ToLower(search_term)
	game_name = strings.ToLower(game_name)

	if search_term == "" {
		return true
	} else if strings.Contains(game_name, search_term) {
		return true
	} else {
		return false
	}
}

func is_match_contains(search_term string, game_name string) bool {
	if search_term == "" {
		return true
	} else if strings.Contains(game_name, search_term) {
		return true
	} else {
		return false
	}
}

func is_match_regex(search_term string, game_name string) bool {
	if search_term == "" {
		return true
	} else if compile_regex(search_term).MatchString(game_name) {
		return true
	} else {
		return false
	}
}

func add_game(game string) {
	if !check_if_game_exists(game) {
		games_added = append(games_added, game)
	}
}

func check_if_game_exists(gameName string) bool {
	game_exists := false
	for _, child := range games_added {
		if child == gameName {
			game_exists = true
		}
	}
	return game_exists
}

func compile_regex(search_term string) *regexp.Regexp {
	regText := ".*"
	for _, letter := range search_term {
		regText += string(letter) + ".*"
	}
	r, _ := regexp.Compile(regText)

	return r
}

func clean_term(term string) string {
	term = strings.ReplaceAll(term, " ", "")
	term = strings.ReplaceAll(term, "é", "e")
	term = strings.ReplaceAll(term, "+", "plus")
	term = strings.ReplaceAll(term, "&", "and")
	term = strings.ReplaceAll(term, "'n", "and")
	return strings.ToLower(term)
}
