package group_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"github.com/bluele/gcache"
	"time"
)

type GroupBanned struct {
	mysql.Entity
	ImGroupId string
	MgrId     uint64
	RuleId    uint64
}

func (banned *GroupBanned) Set(model *domain.Model) error {
	return model.Db.Where(banned).Create(banned).Error
}

func (banned *GroupBanned) Get(model *domain.Model) error {
	return model.Db.Where(banned).First(banned).Error
}

func (banned *GroupBanned) Delete(model *domain.Model) error {
	return model.Db.Where(banned).Delete(&GroupBanned{}).Error
}

var bannedGroupCache = gcache.New(100).LRU().Build()

func GetBannedGroups(model *domain.Model) ([]GroupBanned, error) {
	key := "banned"
	if data, err := bannedGroupCache.Get(key); err == nil {
		model.Log.Infof("GetBannedGroups cache:%v", len(data.([]GroupBanned)))
		return data.([]GroupBanned), nil
	}
	result := make([]GroupBanned, 0)
	err := model.Db.Find(&result).Error
	if err != nil {
		return nil, err
	}
	bannedGroupCache.SetWithExpire(key, result, time.Minute*5)
	return result, nil
}

func GetBannedGroupsMap(model *domain.Model) (map[string]uint64, error) {
	r, err := GetBannedGroups(model)
	if err != nil {
		return nil, err
	}
	result := make(map[string]uint64, 0)
	for _, i := range r {
		result[i.ImGroupId] = i.MgrId
	}
	return result, nil
}