package model

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

	"github.com/jinzhu/gorm"
)

// Alert model
type Alert struct {
	db *gorm.DB
}

// Init init Alert
func (a *Alert) Init(db *gorm.DB) *Alert {
	a.db = db
	return a
}

// Create create a alert rule
func (a *Alert) Create(alert *models.AlarmRule) error {
	err := a.db.Save(alert).Error
	if err == nil {
		cache := getCache()
		key := fmt.Sprintf("Alert:%d", alert.ID)
		cache.Set(key, alert)
	}
	return err
}

// Delete delete a alert rule
func (a *Alert) Delete(alert *models.AlarmRule) error {
	cache := getCache()
	key := fmt.Sprintf("Alert:%d", alert.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	return a.db.Delete(alert).Error
}

// Update 指定厂商ID
func (a *Alert) Update(vendorid string, alert *models.AlarmRule) (data models.AlarmRule, err error) {
	cache := getCache()
	key := fmt.Sprintf("Alert:%d", alert.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	err = a.db.Model(&data).Save(alert).Where("vendor_id = ?", vendorid).Error
	if err == nil {
		cache.Set(key, alert)
	}
	return
}

// GetRules 获取告警列表
// vendorid:厂商ID
// proid:产品ID,可选
// procalid:协议ID, 可选
// name: 规则名称,可选，模糊搜索
func (a *Alert) GetRules(vendorid string, pi, ps, proid, protocalid int, name string) (datas []models.AlarmRule, total int, err error) {
	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
	if proid != 0 {
		tx = tx.Where("product_id = ?", proid)
	}
	if protocalid != 0 {
		tx = tx.Where("protocal_id = ?", protocalid)
	}
	if name != "" {
		tx = tx.Where("alert_name like ?", "%"+name+"%")
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	err = tx.Model(&models.AlarmRule{}).Count(&total).Error
	return
}

// GetAlarmRule 获取数据内容
func (a *Alert) GetAlarmRule(vendorid string, alertid string) (data models.AlarmRule, err error) {
	cache := getCache()
	key := fmt.Sprintf("Alert:%d", alertid)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.AlarmRule)
		data = *_d
	} else {
		err = a.db.Where("vendor_id = ? and record_id = ?", vendorid, alertid).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}

// CheckProtocalRuleCount 返回数据点已经添加的告警数量
func (a *Alert) CheckProtocalRuleCount(vendorid string, protocalID string) (total int, err error) {
	err = a.db.Model(&models.AlarmRule{}).
		Where("vendor_id = ? and protocal_id = ?", vendorid, protocalID).
		Count(&total).
		Error
	return
}

// SetRuleState 设置规则的可用、禁用状态
func (a *Alert) SetRuleState(vendorid string, id string, status int) (data models.AlarmRule, err error) {
	err = a.db.Model(&data).Where("vendor_id = ? and record_id = ?", vendorid, id).
		Update(map[string]interface{}{
			"status": status,
		}).Error
	return
}
