package qznn

import (
	"encoding/json"

	"github.com/sirupsen/logrus"
	gameQZ "nn.daxia.dev/game/qznn"
	"nn.daxia.dev/handler/api"
	"nn.daxia.dev/nxd"
)

type ReadyReq struct {
}

type UnReadyReq struct {
}

type ChooseMasterReq struct {
	Mul int
}

type ChooseMulReq struct {
	Mul int
}

type OpenReq struct {
}

type ConnectReq struct {
}

type DisconnectReq struct {
}

func Ready(req api.PerformReq) error {
	var err error
	userModel := req.UserModel

	readyReq := ReadyReq{}
	err = json.Unmarshal(req.Msg, &readyReq)
	if err != nil {
		logrus.Error(err)
		return err
	}

	gameInstance := gameQZ.GetInstance()
	err = gameInstance.Ready(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 UnReady(req api.PerformReq) error {
	var err error
	userModel := req.UserModel

	unReadyReq := UnReadyReq{}
	err = json.Unmarshal(req.Msg, &unReadyReq)
	if err != nil {
		logrus.Error(err)
		return err
	}

	gameInstance := gameQZ.GetInstance()
	err = gameInstance.UnReady(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 ChooseMaster(req api.PerformReq) error {
	var err error
	userModel := req.UserModel

	chooseMasterReq := ChooseMasterReq{}
	err = json.Unmarshal(req.Msg, &chooseMasterReq)
	if err != nil {
		logrus.Error(err)
		return err
	}

	gameInstance := gameQZ.GetInstance()
	err = gameInstance.ChooseMaster(int32(userModel.ID), int32(chooseMasterReq.Mul))
	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 ChooseMul(req api.PerformReq) error {
	var err error
	userModel := req.UserModel

	chooseMulReq := ChooseMulReq{}
	err = json.Unmarshal(req.Msg, &chooseMulReq)
	if err != nil {
		logrus.Error(err)
		return err
	}

	gameInstance := gameQZ.GetInstance()
	err = gameInstance.ChooseMul(int32(userModel.ID), int32(chooseMulReq.Mul))
	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 Open(req api.PerformReq) error {
	var err error
	userModel := req.UserModel

	openReq := OpenReq{}
	err = json.Unmarshal(req.Msg, &openReq)
	if err != nil {
		logrus.Error(err)
		return err
	}

	gameInstance := gameQZ.GetInstance()
	err = gameInstance.OpenCard(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
}
