package deviceAlarm

import (
	"github.com/gogf/gf/database/gredis"
)

const (
	AlarmPrefix = "device:alarm:"
	dataExpires = 7200
)

type AlarmParams struct {
	DeviceCode      string `json:"device_code"`
	FirstReportTime int64  `json:"first_report_time"`
	LastAlarmTime   int64  `json:"last_alarm_time"`
}

type DevAlarmManager struct {
	redisClient *gredis.Redis
}

func NewDevAlarmManager(host string, port int) *DevAlarmManager {
	red := gredis.New(&gredis.Config{
		Host:      host,
		Port:      port,
		Db:        14,
		MaxActive: 100,
	})
	helper := &DevAlarmManager{
		redisClient: red,
	}
	return helper
}

func (a *DevAlarmManager) SetAlarm(params *AlarmParams) error {
	key := AlarmPrefix + params.DeviceCode
	_, err := a.redisClient.DoVar("SET", key, params)
	if err != nil {
		return err
	}

	_, err = a.redisClient.Do("EXPIRE", key, dataExpires)
	if err != nil {
		return err
	}
	return nil

}

func (a *DevAlarmManager) GetAlarm(code string) (*AlarmParams, error) {
	key := AlarmPrefix + code
	alarm := new(AlarmParams)
	// get status from redis
	result, err := a.redisClient.DoVar("GET", key)
	if err != nil {
		return nil, err
	}
	err = result.Struct(alarm)
	if err != nil {
		return nil, err
	}

	return alarm, nil

}

func (a *DevAlarmManager) DeleteAlarm(code string) error {
	key := AlarmPrefix + code
	// get status from redis
	_, err := a.redisClient.Do("DEL", key)
	if err != nil {
		return err
	}
	return nil

}
