package services

import (
	"errors"
	"github.com/gogf/gf/util/guid"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/model"
)

// AlertService 业务接口
type AlertService interface {
	Create(*models.AlarmRule) error
	Delete(*models.AlarmRule) error
	Update(string, *models.AlarmRule) (models.AlarmRule, error)
	// GetAlarmRules 获取告警列表
	// vendorid:厂商ID
	// proid:产品ID,可选
	// procalid:协议ID, 可选
	// name: 规则名称,可选，模糊搜索
	GetAlarmRules(vendorid string, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error)
	GetRule(vendorid string, alertid string) (models.AlarmRule, error)
	// 设置禁用可用状态
	// 参数(vendorid, recordid, status)
	SetRuleStatus(string, string, int) (models.AlarmRule, error)
}

type alert struct {
	model *model.All
}

// NewAlertService create a alert back a  AlertService interface
func NewAlertService(model *model.All) AlertService {
	return alert{
		model: model,
	}
}

func (a alert) Create(alert *models.AlarmRule) error {
	alert.RecordId = guid.S()
	count, err := a.model.Alert.CheckProtocalRuleCount(alert.VendorID, alert.ProtocalID)
	if err != nil {
		return err
	}
	if count > 0 {
		return errors.New("此协议已经设置告警规则")
	}
	alert.Status = 1

	return a.model.Alert.Create(alert)
}

func (a alert) Delete(alert *models.AlarmRule) error {
	return a.model.Alert.Delete(alert)
}

func (a alert) Update(vendorid string, alert *models.AlarmRule) (models.AlarmRule, error) {
	return a.model.Alert.Update(vendorid, alert)
}
func (a alert) GetAlarmRules(vendorid string, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error) {
	return a.model.Alert.GetRules(vendorid, pi, ps, proid, protocalid, name)
}
func (a alert) GetRule(vendorid string, alertid string) (models.AlarmRule, error) {
	return a.model.Alert.GetAlarmRule(vendorid, alertid)
}
func (a alert) SetRuleStatus(vendorid string, alertid string, status int) (models.AlarmRule, error) {
	return a.model.Alert.SetRuleState(vendorid, alertid, status)
}
