package server

import (
	"game/common/model/user"
	"game/common/proto/pb"
	"game/common/rpc"
	"game/common/utils"
	"github.com/fox/fox/ipb"
	"github.com/fox/fox/ksync"
	"github.com/fox/fox/log"
	"github.com/fox/fox/service"
)

// 匹配房间
func (s *MatchService) onMatchRoom(iMsg *ipb.InternalMsg, req *pb.ReqMatchRoom) {
	ksync.GoSafe(func() {
		// color game无需进入匹配队列
		gameId := req.GameId
		switch gameId {
		case pb.ServiceTypeId_STI_ColorGame:
			node, err := s.BindService().FindServiceNode(gameId, iMsg.UserId)
			if err != nil {
				log.ErrorF("db service node error:%v", err)
				s.SendServiceMsg(pb.ServiceTypeId_STI_Gate, iMsg.UserId, int32(pb.MsgId_RspMatchRoomId), &pb.RspMatchRoom{Code: pb.ErrCode_SystemErr})
				return
			}
			s.SendServiceMsg(pb.ServiceTypeId_STI_Gate, iMsg.UserId, int32(pb.MsgId_RspMatchRoomId), &pb.RspMatchRoom{})
			s.SendServiceMsgByTopic(service.TopicEx(node.Name), iMsg.ConnId, iMsg.UserId,
				int32(pb.MsgId_ReqEnterRoomId), &pb.ReqEnterRoom{})
			return
		}

		var us *user.GameUser
		rsp := &pb.RspMatchRoom{}
		us, rsp.Code = rpc.RpcGetGameUser(s, iMsg.UserId)
		if rsp.Code != pb.ErrCode_OK {
			s.SendServiceMsg(pb.ServiceTypeId_STI_Gate, iMsg.UserId, int32(pb.MsgId_RspMatchRoomId), rsp)
			return
		}
		vipLv, vipExp := utils.VipLevel(us.VipExp)
		rsp.User = &pb.GameUser{
			UserId:      us.ID,
			Nickname:    us.Nickname,
			Avatar:      us.AvatarUrl,
			AvatarFrame: us.AvatarFrame,
			VipLevel:    vipLv,
			VipExp:      vipExp,
			Seat:        0,
			Gold:        us.Gold,
		}
		rsp.GameId = req.GameId
		rsp.RoomType = req.RoomType
		switch pb.ServiceTypeId(rsp.GameId) {
		case pb.ServiceTypeId_STI_ColorGame:
			rsp.ColorInfo = &pb.RspMatchRoom_ColorInfo{}
		}

		s.SendServiceMsg(pb.ServiceTypeId_STI_Gate, iMsg.UserId, int32(pb.MsgId_RspMatchRoomId), rsp)
	}, nil)
}

// 匹配房间
func (s *MatchService) onUserOffline(iMsg *ipb.InternalMsg, ntf *pb.NtfUserOffline) {
	_ = iMsg
	log.DebugF(s.Log("收到玩家下线消息:%v，从匹配队列中移除该玩家", ntf.UserId))
}
