package controllers

import (
	"github.com/astaxie/beego"

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

	"fmt"
	"strconv"
)

type SensorsController struct {
	beego.Controller
}

func (c *SensorsController) Prepare() {
	sess := c.GetSession(variables.SessionName)
	if sess == nil {
		c.Redirect(variables.LoginRouteNoRegex+variables.SensorsRoute, 302)
	} else {
		c.Data["IsAuthentificated"] = true
	}

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

func (c *SensorsController) Get() {
	sensors := sensor.GetAllSensor()
	relays := relay.GetAllRelay()

	c.Data["sensors"] = sensors
	c.Data["relays"] = relays
	c.TplNames = "sensors.tpl"
}

func (c *SensorsController) Post() {
	tpye := c.Input().Get("type")
	if tpye == "tempSensor" {
		c.PostTempSensors()
	} else if tpye == "relay" {
		c.PostRelay()
	} else {
		c.Redirect("/404", 404)
	}
}

func (c *SensorsController) PostTempSensors() {
	description := c.Input().Get("description")
	mac := c.Input().Get("mac")
	intervalStr := c.Input().Get("interval")
	interval, err := strconv.ParseInt(intervalStr, 10, 0)

	isDelete := c.Input().Get("delete")
	fmt.Println("Del: ", isDelete)
	isSave := c.Input().Get("save")
	fmt.Println("Save: ", isSave)
	if isSave != "" && err == nil {
		sensor.UpdateSensor(mac, description, interval)
		c.Redirect("/sensors", 302)
	} else if isDelete != "" {
		s := sensor.GetSensorByMac(mac)
		temperature.DeleteTemperatureBySenor(s.Id)
		sensor.DeleteSensor(s.Id)
		c.Redirect("/sensors", 302)
	} else {
		c.Redirect("/404", 404)
	}
}

func (c *SensorsController) PostRelay() {
	description := c.Input().Get("description")
	mac := c.Input().Get("mac")

	isDelete := c.Input().Get("delete")
	fmt.Println("Del: ", isDelete)
	isSave := c.Input().Get("save")
	fmt.Println("Save: ", isSave)
	if isSave != "" {
		relay.UpdateSensorDescription(mac, description)
		c.Redirect("/sensors", 302)
	} else if isDelete != "" {
		s := relay.GetRelayByMac(mac)
		relay.DeleteSensor(s.Id)
		c.Redirect("/sensors", 302)
	} else {
		c.Redirect("/404", 404)
	}
}
