<?php

/**
 * PacketCacheModel.php
 * 文件描述
 * Created On 2022/2/15
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Framework\Model;

use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\Protobuf\InternalPacket;
use Framework\Protobuf\SinglePacket;
use Framework\DB\Handler\PlayerDBHandler;
use Game\Config\GameConfig;
use Game\Constant\DBTableDefine;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Protobuf\PacketId;
use Google\Protobuf\Internal\Message;

class PacketCacheModel
{
    use PlayerDBHandler;

    public int $playerId;

    public function setPlayerId($playerId)
    {
        $this->playerId = $playerId;
    }

    public function getModelType(): int
    {
        return ModelTypeDefine::PACKET_CACHE;
    }

    public function addPacket(int $packetId, Message $packet, int $playerID = 0): bool
    {
        $packetStr = base64_encode($packet->serializeToString());
        if($playerID == 0 )
        {
            $playerID = $this->playerId;
        }

        $packetMsg = new SinglePacket();
        $packetMsg->setId($packetId);
        $packetMsg->setData($packetStr);
        $data = base64_encode($packetMsg->serializeToString());
        $res = $this->addQueue(
            DBTableDefine::TABLE_PACKET_CACHE,
            $playerID,
            $data
        );
        LogMark::getInstance()->markInfo("addPacket",
            array(
                'packetID' => $packetId,
                "dataLen" => strlen($data)
            )
        );
        if(!$res) {
            LogMark::getInstance()->markError(GameErrorCode::DATA_CREATE_ERROR,
            '[packet cache] save cache packet error!',
                ['packetID' => $packetId, 'playerID' => $playerID, 'msg' => $data]
            );
            return false;
        }

        $notice = new InternalPacket();
        $notice->setPlayerId($playerID);
        $notice->setPacketId(PacketId::GI_PlayerNotice);
        $notice->setSendTime(Utils::getServerTimestamp());
        $data = base64_encode($notice->serializeToString());

        // 通知消息服 取消息
        if(!$this->insQueueRPush(DBTableDefine::TABLE_SERVICE_PACK,  GameConfig::getInstance()->NOTICE_SERVICE(), $data)){
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_NOTICE_SERVICE_ERROR,
                '[send notice service] save data error!',
                [
                    'packetID'    => $packetId,
                    'sendServer'    => GameConfig::getInstance()->NOTICE_SERVICE(),
                    'playerID'    => $playerID,
                    'time'     => Utils::getServerTimestamp(),
                ]
            );
            return false;
        }

        return true;
    }

    public function clearPacket(): bool
    {
        return $this->deleteQueueTitle(
            DBTableDefine::TABLE_PACKET_CACHE,
            $this->playerId
        );
    }
}
