package configindb

import (
	"fmt"
	"sync"

	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/model/legacymodel"
)

type ConfigNotifier func(key, value string)

var (
	legalUsers = map[string]int{
		"zhaominfu":     1,
		"shifeng@2018":  1,
		"zhouyang_2018": 1,
		"xujianhua":     1,
	}
	configNotifierMap = sync.Map{}
)

func ListConfig(key string) (configList []*legacymodel.Config, err error) {
	sql := `
	SELECT *
	FROM config
	`
	sqlParams := []interface{}{}
	if key != "" {
		sql += " WHERE thirdparty = ?"
		sqlParams = append(sqlParams, key)
	}
	db := dao.GetDB()
	if err = dao.GetRows(db, &configList, sql, sqlParams...); err != nil {
		return nil, err
	}
	return configList, nil
}

func GetConfig(key, defValue string) (value string, err error) {
	configList, err := ListConfig(key)
	if err != nil {
		return "", err
	}
	if len(configList) == 0 {
		return defValue, nil
	}
	return configList[0].Token, nil
}

func SetConfig(ctx *jxcontext.Context, key, value string) (num int64, err error) {
	userName := ctx.GetUserName()
	if legalUsers[userName] != 1 {
		return 0, fmt.Errorf("%s不具有此功能操作权限", userName)
	}
	sql := `
	UPDATE config
	SET token = ?,
	date = NOW(),
	last_operator = ?
	WHERE thirdparty = ?
	`
	db := dao.GetDB()
	num, err = dao.ExecuteSQL(db, sql, value, userName, key)
	if err != nil {
		return 0, err
	}
	if num == 0 {
		return 0, fmt.Errorf("没有%s这个配置项", key)
	}
	if v, ok := configNotifierMap.Load(key); ok {
		if notifier, ok := v.(ConfigNotifier); ok {
			notifier(key, value)
		}
	}
	return num, nil
}

func WatchConfigChange(key string, configNotifier ConfigNotifier) {
	configNotifierMap.Store(key, configNotifier)
}
