package model

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

	"github.com/jinzhu/gorm"
)

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

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

// Query query all roles
func (a *RuleNode) Query(pi, ps int, chanId string) (datas []models.RuleNode, total int, err error) {
	tx := a.db.Where("1=1")
	if chanId != "" {
		tx = tx.Where("rule_chain_id = ?", chanId)
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	err = tx.Model(&models.RuleNode{}).Count(&total).Error
	return
}

// Create  创建
func (a *RuleNode) Create(ruleNode *models.RuleNode) error {
	return a.db.Save(ruleNode).Error

}

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

func (a *RuleNode) DeleteByChainId(ruleNode *models.RuleNode) error {
	a.db.Model(&models.RuleNode{}).Where("rule_chan_id = ?", ruleNode.RuleChainID)
	return a.db.Unscoped().Delete(ruleNode).Error
}

// Update update
func (a *RuleNode) Update(ruleNode *models.RuleNode) error {
	return a.db.Save(ruleNode).Error
}
