package rpc

import (
	"encoding/json"
	"game/common/model/user"
	"game/common/proto/pb"
	"github.com/fox/fox/ipb"
	"github.com/fox/fox/log"
	"github.com/fox/fox/service"
	"time"
)

const (
	timeout = time.Second * 30
)

// 获取玩家数据
func RpcGetGameUser(s service.IService, uid int64) (*user.GameUser, pb.ErrCode) {
	us := &user.GameUser{
		User: user.User{
			ID: uid,
		},
		UserResources: user.UserResources{
			UID: uid,
		},
	}
	rpcMsg := ipb.MakeRpcMsg(GetGameUser, uid, us)
	log.DebugF("%v call rpc:%v", s.Name(), GetGameUser)
	rspMsg, err := s.CallByServiceId(int(pb.ServiceTypeId_STI_DB), timeout, rpcMsg)
	if err != nil {
		log.ErrorF("call rpc:%v err:%s ", rpcMsg.RpcMsgId, err.Error())
		return nil, pb.ErrCode_SystemErr
	}
	if rspMsg.RpcCode == 0 {
		_ = json.Unmarshal(rspMsg.Msg, us)
		return us, pb.ErrCode_OK
	}
	return nil, pb.ErrCode(rspMsg.RpcCode)
}

// 获取玩家数据
func RpcGetAccountByUid(s service.IService, uid int64) (*user.UserAccount, pb.ErrCode) {
	us := &user.UserAccount{
		ID: uid,
	}
	rpcMsg := ipb.MakeRpcMsg(GetUserAccountById, uid, us)
	log.DebugF("%v call rpc:%v", s.Name(), GetUserAccountById)
	rspMsg, err := s.CallByServiceId(int(pb.ServiceTypeId_STI_DB), timeout, rpcMsg)
	if err != nil {
		log.ErrorF("call rpc:%v err:%s ", rpcMsg.RpcMsgId, err.Error())
		return nil, pb.ErrCode_SystemErr
	}
	if rspMsg.RpcCode == 0 {
		_ = json.Unmarshal(rspMsg.Msg, us)
		return us, pb.ErrCode_OK
	}
	return nil, pb.ErrCode(rspMsg.RpcCode)
}
