package temperature

import (
	"github.com/astaxie/beego/orm"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/database"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/utils"

	"time"
)

type TempTable struct {
	Id          int64
	HorodateGMT time.Time `orm:"auto_now;type(datetime)"`
	SensorID    int64
	Value       int64
}

func init() {
	orm.RegisterModel(new(TempTable))
}

/**
 * Add the value into the database.
 */
func AddData(sensor, value int64) {
	o := orm.NewOrm()
	o.Using(database.Alias)

	tmpTable := new(TempTable)
	tmpTable.Value = value
	tmpTable.SensorID = sensor
	o.Insert(tmpTable)
}

func GetAllTempForSensor(sensorId int64) []TempTable {
	o := orm.NewOrm()
	o.Using(database.Alias)

	var dataArray []TempTable
	var maps []orm.Params
	_, err := o.QueryTable(new(TempTable)).Filter("SensorID", sensorId).Values(&maps)
	if err == nil {
		for _, m := range maps {
			d := new(TempTable)
			d.Id = utils.GetInt(m, "Id")
			d.HorodateGMT = utils.GetTime(m, "HorodateGMT")
			d.SensorID = utils.GetInt(m, "SensorID")
			d.Value = utils.GetInt(m, "Value")

			dataArray = append(dataArray, *d)
		}
	}
	return dataArray
}

func GetLastTempForSensor(sensorId int64) *TempTable {
	o := orm.NewOrm()
	o.Using(database.Alias)

	data := new(TempTable)
	var maps []orm.Params
	_, err := o.QueryTable(new(TempTable)).Filter("SensorID", sensorId).OrderBy("HorodateGMT").Values(&maps)
	if err == nil {
		for _, m := range maps {
			data.Id = utils.GetInt(m, "Id")
			data.HorodateGMT = utils.GetTime(m, "HorodateGMT")
			data.SensorID = utils.GetInt(m, "SensorID")
			data.Value = utils.GetInt(m, "Value")
		}
	}
	return data
}

func DeleteTemperatureBySenor(sensorId int64) {
	o := orm.NewOrm()
	o.Using(database.Alias)

	temps := GetAllTempForSensor(sensorId)
	for _, temp := range temps {
		o.Delete(&TempTable{Id: temp.Id})
	}
}
