package soilMoisture

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

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

    "time"
)

const (
  MacModuleWifiArduino = "MAC"
  PinArduino           = "PIN"
  ValeurCapteur        = "VAL"
)

var (
	_, timezoneOffset = time.Now().Zone()
	log = logs.NewLogger(10000)
)

func init() {
	log.SetLogger(variables.LogType, variables.LogParams)
	orm.RegisterModel(new(SoilMoistureTable),new(CapteurSoilMoistureTable))
	orm.DefaultRowsLimit = database.RowLimit
}

//——————————————————————————————————————————————————————————————————————————————
//                           SoilMoistureTable
//——————————————————————————————————————————————————————————————————————————————

type SoilMoistureTable struct {
  Id               int64
  HorodateGMT      time.Time  `orm:"auto_now;type(datetime)"`
  CapteurPin       string // Pin Arduino
  MacId            string // Id Bac à Fleur
  ValeurCapteur    int64
}

func AddData(pinCapteur string, macId string, valeur int64) {
	log.Info("Add soilMoisture {BacMac: %s, pinArduino: %s, valeur: %d}", macId, pinCapteur, valeur)
	o := orm.NewOrm()
	o.Using(database.Alias)

    ti := new(SoilMoistureTable)
    ti.CapteurPin = pinCapteur
    ti.ValeurCapteur = valeur
    ti.MacId = macId
    o.Insert(ti)
}

//——————————————————————————————————————————————————————————————————————————————
//                           CapteurSoilMoistureTable
//——————————————————————————————————————————————————————————————————————————————
type CapteurSoilMoistureTable struct {
	Id                int64
	MacArduino        string
	PinArduino        string
	Description       string
}

func GetCapteurByAdresse(mac string, pin string) *CapteurSoilMoistureTable {
	o := orm.NewOrm()
	o.Using(database.Alias)

	ret := new(CapteurSoilMoistureTable)
	var maps []orm.Params
	_, err := o.QueryTable(new(CapteurSoilMoistureTable)).Filter("MacArduino", mac).Filter("PinArduino", pin).Values(&maps)
	if err == nil {
		for _, m := range maps {
			ret.Id = utils.GetInt(m, "Id")
			ret.MacArduino = utils.GetString(m, "MacArduino")
			ret.PinArduino = utils.GetString(m, "PinArduino")
			ret.Description = utils.GetString(m, "Description")
			break
		}
	}

	return ret
}

func AddCapteur(mac string, pin string) {
	o := orm.NewOrm()
	o.Using(database.Alias)
	_, _ = o.Insert(&CapteurSoilMoistureTable{MacArduino: mac, PinArduino: pin})
}
