package common

import (
	"errors"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gogs.daxia.dev/huanan/pkg.daxia.dev/webutils"
	gameQZ "nn.daxia.dev/game/qznn"
	"nn.daxia.dev/handler/api"
	"nn.daxia.dev/handler/qznn"
	"nn.daxia.dev/handler/room"
	"nn.daxia.dev/nxd"
)

func Dispatch(c *gin.Context) {
	var err error

	reqData := api.PerformReq{}
	if err := c.ShouldBindJSON(&reqData); err != nil {
		logrus.Error(err)
		webutils.FailedResponseErr(c, err)
		return
	}

	if reqData.Name != "connect" && reqData.Name != "ping" {
		userModel := reqData.UserModel
		isActive := gameQZ.UserIsOnline(userModel.ID)
		if !isActive {
			logrus.Error("用户不在线")
			webutils.FailedResponse(c, "用户不在线")
			return
		}
	}

	logrus.Info("run function:", reqData.Name)

	switch reqData.Name {
	case "connect":
		err = Connect(reqData)
	case "disconnect":
		err = Disconnect(reqData)
	case "ping":
		err = Ping(reqData)
	case "room/join":
		err = room.Join(reqData)
	case "room/rnd_join":
		err = room.RndJoin(reqData)
	case "room/leave":
		err = room.Leave(reqData)
	case "room/create":
		err = room.Create(reqData)
	case "qznn/ready":
		err = qznn.Ready(reqData)
	case "qznn/unready":
		err = qznn.UnReady(reqData)
	case "qznn/choose_master":
		err = qznn.ChooseMaster(reqData)
	case "qznn/choose_mul":
		err = qznn.ChooseMul(reqData)
	case "qznn/open":
		err = qznn.Open(reqData)
	default:
		logrus.Error("非法请求:", reqData)
		err = errors.New("非法请求")
	}

	if err != nil {
		logrus.Error(err)
		webutils.FailedResponseErr(c, err)
		return
	}

	webutils.SuccessResponse(c, nil)
}

func Test(req api.PerformReq) error {
	userModel := req.UserModel
	fmt.Println(userModel)

	return nil
}

func Connect(req api.PerformReq) error {
	userModel := req.UserModel

	gameInstance := gameQZ.GetInstance()

	err := gameInstance.Connect(int32(userModel.ID))
	if err != nil {
		logrus.Error(err)

		nxd.FailedResponse(req.Once, uint32(userModel.ID), err.Error())
		return err
	}

	nxd.SuccessResponse(req.Once, uint32(userModel.ID), nil)
	return nil
}

func Disconnect(req api.PerformReq) error {
	userModel := req.UserModel

	gameQZ.UserUnActive(userModel.ID)

	return nil
}

func Ping(req api.PerformReq) error {
	userModel := req.UserModel

	gameQZ.UserActive(userModel.ID)

	return nil
}
