package model

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

	"github.com/jinzhu/gorm"
)

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

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

// Query query all roles
func (a *Relation) Query(pi, ps int, chanId string) (datas []models.Relation, 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.Relation{}).Count(&total).Error
	return
}

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

// Create  create
func (a *Relation) Create(relation *models.Relation) error {
	return a.db.Save(relation).Error

}

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

//func (a *Relation) DeleteByChainId(relation *models.Relation) error {
//	a.db.Model(&models.Relation{}).Where("rule_chan_id = ?", relation.RuleChainId)
//	return a.db.Delete(relation).Error
//}

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