package sdk

import (
	mhayaGin "github.com/mhaya/components/gin"
	mhayaError "github.com/mhaya/error"
	mhayaString "github.com/mhaya/extend/string"
	cfacade "github.com/mhaya/facade"
	"github.com/mhaya/game/game_cluster/internal/data"
)

// sdk平台类型
const (
	DevMode  int = 1 // 开发模式，注册开发帐号登陆(开发时使用)
	QuickSDK int = 2 // quick sdk
)

var (
	invokeMaps = make(map[int]Invoke)
)

type (
	Invoke interface {
		SdkId() int                                                        // sdk id
		Login(config *data.SdkConfigRow, params Params, callback Callback) // Login 登录验证接口
		PayCallback(config *data.SdkConfigRow, c *mhayaGin.Context)        // PayCallback 支付回调接口
	}

	Params map[string]string

	Callback func(code int32, result Params, error ...error)
)

func (p Params) GetInt(key string, defaultValue ...int) int {
	defVal := 0
	if len(defaultValue) > 0 {
		defVal = defaultValue[0]
	}

	val, found := p[key]
	if !found {
		return defVal
	}

	intVal, ok := mhayaString.ToInt(val)
	if ok {
		return intVal
	}

	return defVal
}

func (p Params) GetString(key string) (string, bool) {
	v, ok := p[key]
	return v, ok
}

func register(invoke Invoke) {
	invokeMaps[invoke.SdkId()] = invoke
}

func GetInvoke(sdkId int) (invoke Invoke, error error) {
	invoke, found := invokeMaps[sdkId]
	if found == false {
		return nil, mhayaError.Errorf("[sdkId = %d] not found.", sdkId)
	}

	return invoke, nil
}

func Init(app cfacade.IApplication) {
	register(quickSdk{app})
}
