package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type Surfer struct {
	Athlete  Athlete `json:"surfer"`
	Color    string  `json:"color"`
	Priority string  `json:"priority"`
	Score    string  `json:"score"`
}

type Heat struct {
	Round    string   `json:"round"`
	Category string   `json:"category"`
	Number   int      `json:"number"`
	Timer    int      `json:"timer"`
	Status   string   `json:"status"`
	Surfers  []Surfer `json:"surfers"`
}

func heatName(heat Heat) string {
	str := fmt.Sprintf("%s.%d.%s", heat.Round, heat.Number, heat.Category)
	str = strings.ReplaceAll(str, " ", "_")
	return str
}

func (app *App) SaveHeat(c *gin.Context) {
	var heat Heat

	err := c.ShouldBind(&heat)

	if err != nil {
		log.Printf("req error: %+v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Printf("heat: %+v", heat)

	heat.Status = "idle"

	err = app.DB.Write("Heat", heatName(heat), heat)
	if err != nil {
		log.Printf("set error: %+v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"status": fmt.Sprintf("Error: %+v", err)})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "saved"})
}

func (app *App) LoadHeats(c *gin.Context) {
	heats := app.DB.loadHeats()

	c.JSON(http.StatusOK, heats)

	log.Printf("heats: %+v", heats)
}
