package main

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

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

type Athlete struct {
	Firstname string `json:"firstname"`
	Lastname  string `json:"lastname"`
	Category  string `json:"category"`
}

func surferName(athlete Athlete) string {
	str := fmt.Sprintf("%s.%s.%s", athlete.Firstname, athlete.Lastname, athlete.Category)
	str = strings.ReplaceAll(str, " ", "_")
	return str
}

func (app *App) LoadSurfers(c *gin.Context) {
	surfers := app.DB.loadSurfers()

	c.JSON(http.StatusOK, surfers)

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

func (app *App) SaveSurfer(c *gin.Context) {
	var athlete Athlete

	err := c.ShouldBind(&athlete)

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

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

	err = app.DB.Write("Surfers", surferName(athlete), athlete)
	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"})
}
