package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	scribble "github.com/nanobox-io/golang-scribble"
)

type Surfer struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	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

	// body, _ := io.ReadAll(c.Request.Body)

	// log.Printf("save: %+v", string(body))

	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)
}

func (app *App) DeleteHeat(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)

	err = app.DB.Delete("Heat", heatName(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": "deleted"})
}

func (app *App) StartHeatTimer(c *gin.Context) {
	var msg Message
	var err error
	var timer time.Duration

	if app.Stream.HeatRunning {
		c.JSON(http.StatusOK, "running")
		return
	}

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

	heat := &Heat{}

	json.Unmarshal([]byte(msg.Data), heat)

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

	timer, err = time.ParseDuration(strconv.Itoa(heat.Timer) + "m")
	if err != nil {
		log.Printf("req error: %+v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	app.Stream.HeatTimer = timer
	app.Stream.HeatRunning = true

	// app.startHeat()

	log.Printf("start timer %s - received %s", app.Stream.HeatTimer, heat.Timer)
	c.JSON(http.StatusOK, app.Stream.HeatRunning)
}

// func (app *App) StopHeatTimer(c *gin.Context) {
// 	if !app.Stream.Start {
// 		c.JSON(http.StatusOK, app.Stream.Duration)
// 		return
// 	}

// 	stopHeat(app.DB, *app.Stream.Heat)
// 	app.Stream.Start = false
// 	app.Stream.Duration = 0

// 	log.Printf("start timer %s", app.Stream.Duration)
// 	c.JSON(http.StatusOK, app.Stream.Duration)
// }

func (app *App) startHeat(heat Heat) error {
	log.Printf("heat: %+v", heat)

	heat.Status = "running"

	err := app.DB.Write("Heat", heatName(heat), heat)
	if err != nil {
		log.Printf("set error: %+v", err)
		return err
	}

	return nil
}

func stopHeat(db *scribble.Driver, heat Heat) error {

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

	heat.Status = "ended"

	err := db.Write("Heat", heatName(heat), heat)
	if err != nil {
		log.Printf("set error: %+v", err)
		return err
	}

	return nil
}
