package controllers

import (
	"strconv"
	"time"

	"github.com/astaxie/beego"

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

type AddTempController struct {
	beego.Controller
}

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

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

func (c *AddTempController) Get() {
	mac := c.Ctx.Input.Param(":sensor")
	val, _ := strconv.Atoi(c.Ctx.Input.Param(":val"))

	s := sensor.GetSensorByMac(mac)
	if s == nil || s.Id == 0 {
		sensor.AddSensor(mac)
		s = sensor.GetSensorByMac(mac)
	}

	addToTempBdd(s, val)
	saveInBDD(s, val)

	c.Ctx.Output.Body([]byte(strconv.FormatInt(s.Interval, 10)))
}

/**
 * Save into temporaire database.
 */
func addToTempBdd(snsor *sensor.SensorTable, val int) {
	nowUTC := time.Now().UTC()
	tempTmp := temperatureTmp.GetTemp(snsor.Id)
	if tempTmp == nil || tempTmp.Id == 0 { // Add new entry for sensor
		temperatureTmp.AddData(snsor.Id, int64(val))
	} else { // Update entry for sensor
		temperatureTmp.UpdateTemp(snsor.Id, int64(val), nowUTC)
	}
}

/**
 * Save into database.
 */
func saveInBDD(snsor *sensor.SensorTable, val int) {
	nowUTC := time.Now()
	lastTempRecord := temperature.GetLastTempForSensor(snsor.Id)
	intervalTmp := nowUTC.Unix() - lastTempRecord.HorodateGMT.Unix() - int64(timezoneOffset)
	if intervalTmp >= snsor.Interval {
		temperature.AddData(snsor.Id, int64(val))
	}
}
