package api

import (
	"net/http"
	"strconv"
	"th7/data/core"

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

// helper functions

func (g *GinAdapter) getRatio() core.Ratio {
	return g.corePort.GetRatio()
}

func (g *GinAdapter) getChannels() []core.Channel {
	return g.corePort.GetChannels()
}

func (g *GinAdapter) getChannelByID(id int) (core.Channel, error) {
	return g.corePort.GetChannel(id)
}

/*************************************************************************/
/*************************************************************************/
/*************************************************************************/

func (g *GinAdapter) GetChannelByIDHandler(c *gin.Context) {
	var timestamp string
	id, err := strconv.Atoi(c.Param("id"))

	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	channel, err := g.getChannelByID(id)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	timestamp = g.getTimestamp()
	c.JSON(http.StatusOK, gin.H{
		"channel": channel,
		"time":    timestamp,
	})
}

func (g *GinAdapter) GetChannelsHandler(c *gin.Context) {
	channels := g.getChannels()
	timestamp := g.getTimestamp()

	c.JSON(http.StatusOK, gin.H{
		"channels": channels,
		"time":     timestamp,
	})
}

func (g *GinAdapter) GetRatioHandler(c *gin.Context) {
	ratio := g.getRatio()
	timestamp := g.getTimestamp()

	c.JSON(http.StatusOK, gin.H{
		"ratio": ratio,
		"time":  timestamp,
	})
}

func (g *GinAdapter) GetDataHandler(c *gin.Context) {
	timestamp := g.getTimestamp()
	ratio := g.getRatio()
	channels := g.getChannels()

	c.JSON(http.StatusOK, gin.H{
		"channels": channels,
		"ratio":    ratio,
		"time":     timestamp,
	})
}