package controllers

import (
	"github.com/astaxie/beego"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/sensor"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/temperature"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"

	"html/template"
	"strconv"
)

type ViewTempController struct {
	beego.Controller
}

func (c *ViewTempController) Prepare() {
	sess := c.GetSession(variables.SessionName)
	if sess != nil {
		c.Data["IsAuthentificated"] = true
	}

	c.Data["IsViewTemp"] = true
	c.Data["version"] = variables.Version
}

func (c *ViewTempController) Get() {
	dataTemp := ""
	sensors := sensor.GetAllSensor()
	for i := 0; i < len(sensors); i++ {
		if i > 0 {
			dataTemp += ","
		}

		desc := sensors[i].Description
		if desc == "" {
			desc = sensors[i].SensorMAC
		}
		dataTemp += formatDataSensor(desc, temperature.GetAllTempForSensor(sensors[i].Id))
	}

	c.Data["dataTemp"] = template.JS(dataTemp)
	c.TplNames = "temp.tpl"
}

/*
--------------------------------------------------------------------------------
*/

func formatDataSensor(sensorName string, values []temperature.TempTable) string {
	ret := "{name : \"" + sensorName + "\",marker : {enabled : true, radius : 3}, data : ["
	for i := 0; i < len(values); i++ {
		if i > 0 {
			ret += ","
		}
		horodate := strconv.FormatInt((values[i].HorodateGMT.Unix()+int64(timezoneOffset))*1000, 10)
		value := strconv.FormatInt(values[i].Value, 10)
		ret += "[" + horodate + "," + value + "]"
	}
	ret += "]}"
	return ret
}
