package filterPoly

import (
	log "app.yhyue.com/moapp/jylog"
	"bp.jydev.jianyu360.cn/BaseService/gateway/common"
	"bp.jydev.jianyu360.cn/BaseService/gateway/common/db"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

const DefaultRule = "default"

type Manager struct {
	data map[string]*ReqFilterPoly
}

func InitFilterPolyManager() *Manager {
	manager := &Manager{
		data: map[string]*ReqFilterPoly{},
	}
	res := db.GateWatMySql.Query(`SELECT * FROM front_proxy_ploy`)
	if res != nil && len(*res) > 0 {
		for _, rule := range *res {
			code := gconv.String(rule["code"])
			var reqRule ReqRule
			if err := gconv.Scan(rule["ploy_rule"], &reqRule); err != nil {
				log.Errorf("格式化%s策略异常 %v", code, err)
				continue
			}
			manager.AddRule(code, &reqRule)
		}
	}
	manager.initCache()
	syncBlackWhiteList()
	return manager
}

func (receiver *Manager) initCache() {
	var conf common.RedisConf
	ctx := gctx.New()
	if err := g.Cfg().MustGet(ctx, "databases.polyredis").Scan(&conf); err != nil {
		log.WithContext(ctx).Errorf("redis初始化异常 %v", err)
	}
	AllRedis = common.InitRedis(conf)
}

// AddRule 添加规则
func (receiver *Manager) AddRule(code string, rule *ReqRule) {
	receiver.data[code] = &ReqFilterPoly{
		Code: code,
		Rule: rule,
	}
}

// GetRule 获取规则
func (receiver *Manager) GetRule(code string) (rule *ReqFilterPoly) {
	var ok bool
	rule, ok = receiver.data[code]
	if !ok {
		rule, ok = receiver.data[DefaultRule]
		if !ok {
			return &ReqFilterPoly{
				Code: DefaultRule,
				Rule: &ReqRule{
					Alias:      "",
					CheckWhite: false,
					CheckBlack: false,
				},
			}
		}
	}
	return rule
}
