<?php

/**
 * 发送消息给服务
 * Created On 2022/08/31
 */

namespace Framework\Network;

use Library\Common\Singletons;
use Library\Crypt;
use Framework\Log\LogMark;
use Framework\Protobuf\ClientError;
use Framework\Protobuf\InternalPacket;
use Game\Constant\DBTableDefine;
use Game\Protobuf\PacketId;
use Framework\DB\Handler\CommonDBHandler;
use Gm\Config\ErrorCode;
use Google\Protobuf\Internal\Message;
use Game\Config\GameConfig;

/**
 * 发送消息管理类
 */
class SendServiceMsg
{
    use CommonDBHandler;
    use Singletons;
    use Crypt;

    /**
     * @var InternalPacket $respond_msg 发送给客户端的响应消息
     */
    private InternalPacket $respond_msg;

    /**
     * 初始化模块
     */
    public function init()
    {
    }

    /**
     * 添加发送给客户端的消息包
     */
    public function sendServiceMsg(int $packetID, string $sendServer, Message $packet, int $playerID = 0,
                                   int $sendTime = 0)
    {
        $this->respond_msg = new InternalPacket();
        $this->respond_msg->setPacketId($packetID);
        $this->respond_msg->setSendServer($sendServer);
        $this->respond_msg->setPacketData(base64_encode($packet->serializeToString()));
        $this->respond_msg->setPlayerId($playerID);
        $this->respond_msg->setSendTime($sendTime);
        $data = base64_encode($this->respond_msg->serializeToString());

        $timeout = GameConfig::getInstance()->SERVICE_SAVE_DATA_TIMEOUT();

        LogMark::getInstance()->markInfo(
            '[service] save msg to db !',
            [
                'packetID'    => $packetID,
                'sendServer'    => $sendServer,
                'playerID'    => $playerID,
                'time'     => $sendTime,
            ]
        );

        if(!$this->insQueueRPushCommon(DBTableDefine::TABLE_SERVICE_PACK,  $sendServer, $data)){
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_GM_INTERNAL,
                '[service] send data error!',
                [
                    'packetID'    => $packetID,
                    'sendServer'    => $sendServer,
                    'playerID'    => $playerID,
                    'time'     => $sendTime,
                ]
            );
        }
        if(!$this->setKeyExpire(DBTableDefine::TABLE_SERVICE_PACK, $sendServer, $timeout)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_GM_INTERNAL,
                '[service] key set expire error!',
                [
                    'sendServer'    => $sendServer,
                    'timeout' => $timeout
                ]
            );
        }

    }

    /**
     * @param int $errorId 错误id
     * @param string $sendServer
     */
    public function sendServiceErrorClient(int $errorId, string $sendServer)
    {
        $packet = new ClientError();
        $packet->setErrorId($errorId);
        $this->sendServiceMsg(PacketId::Server_Error, $sendServer, $packet);
    }

}
