package main

import (
	"fmt"
	"strings"
	"time"
)

type DisplayTable interface {
	AddPlayer(player HypixelPlayer)
	AddPlayerN(player string, app *App)
	Draw()
	GetPlayers() []HypixelPlayer
}

type BedwarsDisplayTable struct {
	players []HypixelPlayer
}

func (b *BedwarsDisplayTable) GetPlayers() []HypixelPlayer {
	return b.players
}

func (b *BedwarsDisplayTable) AddPlayer(player HypixelPlayer) {
	b.players = append(b.players, player)
}

func (b *BedwarsDisplayTable) AddPlayerN(player string, app *App) {
	cachedPlayer, isAlive := app.UUIDCache.Get(player)

	if isAlive {
		fetchedPlayer, err := app.API.FetchPlayer(cachedPlayer.Uuid)
		if err != nil {
			fmt.Println("Error fetching player from Hypixel API:", err)
			return
		}
		b.AddPlayer(fetchedPlayer.Player)
	} else {
		playerData, err := FetchMCPlayer(player)
		if err != nil {
			fmt.Println("Error fetching player data:", err)
			return
		}

		app.UUIDCache.Add(&CachedUuid{
			CleanUuid:   strings.ReplaceAll(playerData.UUID, "-", ""),
			Uuid:        playerData.UUID,
			PlayerName:  playerData.Username,
			TimeFetched: time.Now(),
		})

		fetchedPlayer, err := app.API.FetchPlayer(playerData.UUID)
		if err != nil {
			fmt.Println("Error fetching player from Hypixel API:", err)
			return
		}
		b.AddPlayer(fetchedPlayer.Player)
	}
}

func (b *BedwarsDisplayTable) Draw() {
	fmt.Println("=== Bedwars Player Table ===")
	for _, player := range b.players {
		fmt.Printf("Player: %s, Score: %d\n", player.DisplayName, player.Achievements.BedwarsStar)
	}
}
