package nxd

import (
	"fmt"

	"github.com/gookit/event"
	"github.com/sirupsen/logrus"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/known/anypb"
	"nn.daxia.dev/gameproto"
	"nn.daxia.dev/model"
	"nn.daxia.dev/online"
)

//提供基础接口给业务使用，相当于业务模块的sdk
func SendMsgToUser(recvUserID uint32, msg online.Msg) {
	evnetUser := model.EventNotifyMsg + fmt.Sprintf("user_%d", recvUserID)
	event.MustFire(evnetUser, event.M{
		"msg": msg,
	})
}

func SendMsgToUserList(recvUserIDList []int32, notifyType gameproto.NotifyTypeEnum, dataSend protoreflect.ProtoMessage) {
	data, err := proto.Marshal(dataSend)
	if err != nil {
		logrus.Error(err)
		return
	}

	msg := online.Msg{
		NotifyType: uint32(notifyType),
		Data:       string(data),
	}

	for _, recvUserID := range recvUserIDList {
		evnetUser := model.EventNotifyMsg + fmt.Sprintf("user_%d", recvUserID)
		event.MustFire(evnetUser, event.M{
			"msg": msg,
		})
	}
}

func SendMsgToAllUser(msg online.Msg) {
	userIDList := online.GetAllUser()
	for _, userID := range userIDList {
		SendMsgToUser(userID, msg)
	}
}

func SendMsgToAllUserK(notifyType gameproto.NotifyTypeEnum, dataSend protoreflect.ProtoMessage) {
	data, err := proto.Marshal(dataSend)

	if err != nil {
		logrus.Error(err)
		return
	}

	userIDList := online.GetAllUser()
	for _, recvUserID := range userIDList {
		SendMsgToUser(recvUserID, online.Msg{
			NotifyType: uint32(notifyType),
			Data:       string(data),
		})
	}
}

func SendMsgToUserK(recvUserID uint32, notifyType gameproto.NotifyTypeEnum, dataSend protoreflect.ProtoMessage) {
	data, err := proto.Marshal(dataSend)

	if err != nil {
		logrus.Error(err)
		return
	}

	SendMsgToUser(recvUserID, online.Msg{
		NotifyType: uint32(notifyType),
		Data:       string(data),
	})
}

func SuccessResponse(once string, recvUserID uint32, dataSend protoreflect.ProtoMessage) {
	var err error

	var any *anypb.Any

	if dataSend != nil {
		any, err = anypb.New(dataSend)
		if err != nil {
			logrus.Error(err)
			return
		}
	}

	data, err := proto.Marshal(&gameproto.MsgResp{
		Once:   once,
		Status: gameproto.RespStatus_RespStatusSucc,
		Msg:    "",
		Data:   any,
	})

	if err != nil {
		logrus.Error(err)
		return
	}

	SendMsgToUser(recvUserID, online.Msg{
		NotifyType: uint32(gameproto.NotifyTypeEnum_NotifyTypeMsgResp),
		Data:       string(data),
	})
}

func FailedResponse(once string, recvUserID uint32, msg string) {
	var err error

	data, err := proto.Marshal(&gameproto.MsgResp{
		Once:   once,
		Status: gameproto.RespStatus_RespStatusFailed,
		Msg:    msg,
		Data:   nil,
	})

	if err != nil {
		logrus.Error(err)
		return
	}

	SendMsgToUser(recvUserID, online.Msg{
		NotifyType: uint32(gameproto.NotifyTypeEnum_NotifyTypeMsgResp),
		Data:       string(data),
	})
}
