package model

import (
	"fmt"
	"sparrow/pkg/models"

	"github.com/jinzhu/gorm"
)

// Sensor ``
type Sensor struct {
	db *gorm.DB
}

// Init 初始化
func (a *Sensor) Init(db *gorm.DB) *Sensor {
	a.db = db
	return a
}

// Create 创建
func (a *Sensor) Create(ptl *models.Sensor) error {
	cache := getCache()
	key := fmt.Sprintf("Sensor:%d", ptl.ID)
	err := a.db.Save(ptl).Error
	if err != nil {
		return err
	}
	cache.Set(key, ptl)
	return nil
}

// Delete 删除
func (a *Sensor) Delete(ptl *models.Sensor) error {
	cache := getCache()
	key := fmt.Sprintf("Sensor:%d", ptl.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	return a.db.Delete(ptl).Error
}

// Update 更新
func (a *Sensor) Update(ptl *models.Sensor) (data models.Sensor, err error) {
	cache := getCache()
	key := fmt.Sprintf("Sensor:%d", ptl.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	err = a.db.Model(&data).Update(ptl).Error
	return
}

// GetProductSensors 获取产品的传感器列表
func (a *Sensor) GetProductSensors(productid uint, pi, ps int, name, label string) (datas []models.Sensor, total int, err error) {
	tx := a.db.Where("product_id = ? and 1 = 1", productid)
	if name != "" {
		tx = tx.Where("name like ? ", "%"+name+"%")
	}
	if label != "" {
		tx = tx.Where("label = ?", label)
	}

	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.Sensor{}).Count(&total)
	return
}

// GetSensorInfo 获取数据点内容
func (a *Sensor) GetSensorInfo(sid uint) (data models.Sensor, err error) {
	cache := getCache()
	key := fmt.Sprintf("Sensor:%d", sid)
	if v, ok := cache.Get(key); ok {
		data = *(v.(*models.Sensor))
	} else {
		err = a.db.Where("id = ?", sid).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}
