package game

import (
	"encoding/json"
	"errors"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gogs.daxia.dev/huanan/pkg.daxia.dev/webutils"
)

//对接游戏用的API
type QznnApi struct {
}

func (p QznnApi) Ready(roomID, userID uint32) (gin.H, error) {
	gameBaseUrl := viper.GetString("game.base_url")

	reqUrl := gameBaseUrl + "/api/bs/qznn/ready"

	readyReq := ReadyReq{
		RoomID: roomID,
		UserID: userID,
	}

	readyReqData, err := json.Marshal(readyReq)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	respData, err := webutils.PostResp[gin.H](reqUrl, string(readyReqData), time.Second*3)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	if respData.Code != webutils.CodeSuccess {
		logrus.Error(respData)
		return nil, errors.New(respData.Msg)
	}

	return respData.Data, nil
}

func (p QznnApi) ChooseMaster(roomID, userID uint32, mul int) (gin.H, error) {
	gameBaseUrl := viper.GetString("game.base_url")

	reqUrl := gameBaseUrl + "/api/bs/qznn/choose_master"

	req := ChooseMasterReq{
		RoomID: roomID,
		UserID: userID,
		Mul:    mul,
	}

	readyReqData, err := json.Marshal(req)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	respData, err := webutils.PostResp[gin.H](reqUrl, string(readyReqData), time.Second*3)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	if respData.Code != webutils.CodeSuccess {
		logrus.Error(respData)
		return nil, errors.New(respData.Msg)
	}

	return respData.Data, nil
}

func (p QznnApi) ChooseMul(roomID, userID uint32, mul int) (gin.H, error) {
	gameBaseUrl := viper.GetString("game.base_url")

	reqUrl := gameBaseUrl + "/api/bs/qznn/choose_mul"

	req := ChooseMulReq{
		RoomID: roomID,
		UserID: userID,
		Mul:    mul,
	}

	readyReqData, err := json.Marshal(req)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	respData, err := webutils.PostResp[gin.H](reqUrl, string(readyReqData), time.Second*3)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	if respData.Code != webutils.CodeSuccess {
		logrus.Error(respData)
		return nil, errors.New(respData.Msg)
	}

	return respData.Data, nil
}

func (p QznnApi) Open(roomID, userID uint32) (gin.H, error) {
	gameBaseUrl := viper.GetString("game.base_url")

	reqUrl := gameBaseUrl + "/api/bs/qznn/open"

	req := OpenReq{
		RoomID: roomID,
		UserID: userID,
	}

	readyReqData, err := json.Marshal(req)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	respData, err := webutils.PostResp[gin.H](reqUrl, string(readyReqData), time.Second*3)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	if respData.Code != webutils.CodeSuccess {
		logrus.Error(respData)
		return nil, errors.New(respData.Msg)
	}

	return respData.Data, nil
}
