package controllers

import (
	"github.com/astaxie/beego"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/teleinfo"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"

	"html/template"
	"strconv"
)

//——————————————————————————————————————————————————————————————————————————————
//                           AddTeleinfoController
//——————————————————————————————————————————————————————————————————————————————
type AddTeleinfoController struct {
	beego.Controller
}

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

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

func (c *AddTeleinfoController) Get() {
	adresse := c.GetString(teleinfo.AdresseCompteur)
	tarif := c.GetString(teleinfo.OptionTarifaire)
	option, _ := c.GetInt(teleinfo.OptionBase)
	isousc, _ := c.GetInt(teleinfo.IntensiteSouscrite)
	iinst, _ := c.GetInt(teleinfo.IntensiteInstantanne)
	imax, _ := c.GetInt(teleinfo.IntensiteMax)
	papp, _ := c.GetInt(teleinfo.PuissanceApparente)

	teleinfo.AddData(adresse, tarif, int64(option), int64(isousc), int64(iinst), int64(imax), int64(papp))

	cpt := teleinfo.GetCompteurByAdresse(adresse)
	if cpt == nil || cpt.Id == 0 {
		teleinfo.AddCompteur(adresse)
	}
	c.Ctx.Output.Body([]byte(""))
}

//——————————————————————————————————————————————————————————————————————————————
//                           ViewTeleinfoController
//——————————————————————————————————————————————————————————————————————————————
type ViewTeleinfoController struct {
	beego.Controller
}

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

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

func (c *ViewTeleinfoController) Get() {
	c.Data["compteurs"] = teleinfo.GetAllCompteur()

	adresse := c.Ctx.Input.Param(":compteur")
	cpt := teleinfo.GetCompteurByAdresse(adresse)
	if cpt.Id != 0 {
		c.Data["isCompteurSelected"] = true
		c.Data["dataCompteur"] = teleinfo.GetLastDataForCompteur(cpt.AdresseCompteur)
		c.Data["compteurAdresse"] = cpt.AdresseCompteur
		desc := cpt.Description
		if desc == "" {
			desc = cpt.AdresseCompteur
		}
		c.Data["compteurDescription"] = desc
		dataPower := formatDataSensorTeleInfo(teleinfo.GetAllDataForCompteur(cpt.AdresseCompteur))
		c.Data["dataPower"] = template.JS(dataPower)
	}

	c.TplName = "teleinfo.tpl"
}

func formatDataSensorTeleInfo(values []teleinfo.TeleinfoTable) string {
	ret := ""
	ret += "{name : \"Puissance apparente (VA)\",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].PuissanceApparente, 10)
		ret += "[" + horodate + "," + value + "]"
	}
	ret += "]}"
	return ret
}
