<?php


namespace Game;


use Framework\Log\LogMark;
use Framework\MVC\ModelManager;
use Framework\Network\ICheckRequest;
use Framework\Network\SendMessage;
use Framework\Protobuf\SinglePacket;
use Game\Constant\ModelTypeDefine;
use Game\Data\AccountData;
use Game\Logic\AccountLogic;
use Game\Model\AccountModel;
use Game\Protobuf\UserLoginSend;

class CheckRequest implements ICheckRequest
{
    use AccountLogic;
    //上次请求缓存信息
    private int $lastIndex = 0;
    private ?string $lastSessionId = null;
    private ?string $packetCache = null;

    public function checkSessionValid($sessionId): bool
    {
        //查询玩家登录信息
        $this->getAccountLoginPacketData();

        //TODO:查询服务器状态

           if (!is_null($this->lastSessionId) &&
            $sessionId != $this->lastSessionId) {
            return false;
        }
        return true;
    }

    public function checkReconnect($packetIndex): bool
    {
        if ($packetIndex == $this->lastIndex) {
            SendMessage::getInstance()->setLastPacketMessage($this->packetCache);
            return true;
        }
        return false;
    }

    private function getAccountLoginPacketData()
    {
        /**
         * @var AccountModel $accountModel
         */
        $accountModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
        $playerInfo = array();
        if ($accountModel->search(GameLive::getInstance()->playerId, $playerInfo)) {
            $this->lastIndex = $playerInfo[AccountData::DB_PACKET_INDEX] ?? 0;
            $this->lastSessionId = $playerInfo[AccountData::DB_SESSION] ?? null;
            $this->packetCache = $playerInfo[AccountData::DB_PACKET_CACHE] ?? null;
        }
    }

    public function sendLoginPacketCache($packet):bool {
        $str = base64_decode($packet->getData());

        $packetMsg = new UserLoginSend();
        $packetMsg->mergeFromString($str);
        $account = $packetMsg->getAccount();

        /**
         * @var AccountModel $accountModel
         */
        $accountModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
        $this->playerId = $this->searchPlayerIdByAccount($account);
        $playerInfo = array();
        if ($accountModel->search($this->playerId, $playerInfo)) {
            $this->lastIndex = $playerInfo[AccountData::DB_PACKET_INDEX] ?? 0;
            $this->lastSessionId = $playerInfo[AccountData::DB_SESSION] ?? null;
            $this->packetCache = $playerInfo[AccountData::DB_PACKET_CACHE] ?? null;
        }
        if(!is_null($this->packetCache)) {
            SendMessage::getInstance()->setLastPacketMessage($this->packetCache);
        }
        return true;
    }
}