package controllers

import (
	"api/models"
	"api/utils"
	"log"

	"github.com/gofiber/fiber/v2"
)

func ServerStart(c *fiber.Ctx) error {
	// Creates a server struct
	s := new(models.LalServer)

	// Parse the body of the request to the server struct
	if err := c.BodyParser(s); err != nil {
		log.Printf("Error Start: %s\n", err)
		return err
	}

	log.Printf("Server started")

	// Marshal the server struct to JSON
	utils.PrettyPrintJson(s)
	return c.SendString("Server started: " + string(c.Body()))
}

func OnUpdate(c *fiber.Ctx) error {
	p := new(models.Update)
	if err := c.BodyParser(p); err != nil {
		log.Printf("Error Update: %s\n", err)
		return err
	}

	log.Printf("Update")
	utils.PrettyPrintJson(p)

	if len(p.Groups) > 0 {
		for _, g := range p.Groups {
			log.Printf("Update %s %s [(%dx%d) %d]\n", g.Channel, g.UpdPub.StartTime, g.VideoWidth, g.VideoHeight, g.UpdPub.ReadBytesSum)
		}
	}

	return c.SendString("On_Update: " + string(c.Body()))
}

func OnSubStart(c *fiber.Ctx) error {
	p := new(models.Update)
	if err := c.BodyParser(p); err != nil {
		log.Printf("Error Update: %s\n", err)
		return err
	}

	log.Printf("SubStart")
	utils.PrettyPrintJson(p)

	// if len(p.Groups) > 0 {
	// 	for _, g := range p.Groups {
	// 		log.Printf("Update %s %s [(%dx%d) %d]\n", g.Channel, g.UpdPub.StartTime, g.VideoWidth, g.VideoHeight, g.UpdPub.ReadBytesSum)
	// 	}
	// }

	return c.SendString("On_Substart: " + string(c.Body()))
}

func OnPubStart(c *fiber.Ctx) error {
	p := new(models.Pub)
	if err := c.BodyParser(p); err != nil {
		return err
	}
	log.Printf("Start %s\n", p.Channel)
	return c.SendString("On_Pub_Start: " + string(c.Body()))
}

func OnPubStop(c *fiber.Ctx) error {
	p := new(models.Pub)
	if err := c.BodyParser(p); err != nil {
		return err
	}
	log.Printf("Stop %s\n", p.Channel)
	return c.SendString("On_Pub_Stop: " + string(c.Body()))
}
