package main

import (
	"bytes"
	"io"
	"log"
	"net/http"

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

type Status struct {
	Surfers []Surfer `json:"surfers"`
	Round   Info     `json:"round"`
	Count   int      `json:"surfersCount"`
}

type Surfer struct {
	Id       string `json:"id"`
	Name     string `json:"name"`
	Color    string `json:"color"`
	Priority string `json:"priority"`
	Score    int    `json:"score"`
	Delete   bool   `json:"delete"`
}

type Info struct {
	Round    string `json:"round"`
	Heat     int    `json:"heat"`
	Category string `json:"category"`
	Time     int    `json:"time"`
}

var status Status

func initStatus() interface{} {
	return Status{
		Surfers: []Surfer{
			{
				Name:     "",
				Color:    "lightgray",
				Priority: "",
				Score:    0,
			},
		},
		Round: Info{
			Round:    "",
			Heat:     1,
			Category: "",
			Time:     0,
		},
		Count: 1,
	}
}

func GetStatus(c *gin.Context) {
	c.JSON(http.StatusOK, status)

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

func SetStatus(c *gin.Context) {
	var stat = Status{}

	body, _ := io.ReadAll(c.Request.Body)
	log.Printf("set status body: %s", string(body))
	c.Request.Body = io.NopCloser(bytes.NewReader(body))

	err := c.ShouldBindJSON(&stat)
	log.Printf("set status: %+v - err: %+v", stat, err)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": stat,
	})

	var msg = Message{
		Data: stat,
	}

	broadcast <- msg

	status = stat
}
