package sdk

import (
	mhayaGin "github.com/mhaya/components/gin"
	cerror "github.com/mhaya/error"
	cstring "github.com/mhaya/extend/string"
	cfacade "github.com/mhaya/facade"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/data"
	rpcCenter "github.com/mhaya/game/game_cluster/internal/rpc/center"
	sessionKey "github.com/mhaya/game/game_cluster/internal/session_key"
)

type quickSdk struct {
	app cfacade.IApplication
}

func (quickSdk) SdkId() int {
	return QuickSDK
}

func (p quickSdk) Login(config *data.SdkConfigRow, params Params, callback Callback) {
	openid, found := params.GetString("openid")
	if found == false || cstring.IsBlank(openid) {
		err := cerror.Error("openid is nil")
		callback(code.LoginError, nil, err)
		return
	}

	ip, found := params.GetString("ip")
	if found == false || cstring.IsBlank(ip) {
		err := cerror.Error("ip is nil")
		callback(code.LoginError, nil, err)
		return
	}

	plt, found := params.GetString("platform")
	if found == false || cstring.IsBlank(plt) {
		err := cerror.Error("platform is nil")
		callback(code.LoginError, nil, err)
		return
	}

	channel, found := params.GetString("channel")
	if found == false || cstring.IsBlank(channel) {
		err := cerror.Error("channel is nil")
		callback(code.LoginError, nil, err)
		return
	}

	/*	url := fmt.Sprintf("%v%v/getChat?chat_id=%v", config.Params.AppUrl, config.Params.BotToken, openid)
		rspBody, _, err := mhayaHttp.GET(url, map[string]string{})

		if err != nil || rspBody == nil {
			callback(code.LoginError, nil, err)
			return
		}

		var result = struct {
			OK bool `json:"ok"`
		}{}
		jsoniter.Unmarshal(rspBody, &result)
		if !result.OK {
			mhayaLogger.Warnf("quick sdk login fail. rsp =%s", rspBody)
			callback(code.LoginError, nil, err)
			return
		}*/

	account := rpcCenter.RegisterAccount(p.app, openid, ip, plt, channel)
	if account == nil {
		callback(code.LoginError, nil)
		return
	}

	callback(code.OK, map[string]string{
		sessionKey.PlayerID:   account.UserName, //返回 quick的uid做为 open id
		sessionKey.OpenID:     openid,
		sessionKey.TargetPath: account.TargetPath,
	})
}

func (s quickSdk) PayCallback(config *data.SdkConfigRow, c *mhayaGin.Context) {
	// TODO 这里实现quick sdk 支付回调的逻辑
	c.RenderHTML("FAIL")
}
