<?php

/**
 * 进入场景 开始比赛
 */

namespace Game\Controller\Pvp;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\MVC\ModelManager;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Constant\GameConstantDefine;
use Game\Constant\ModelTypeDefine;
use Game\Model\Pvp\PvpBaseModel;
use Game\Model\RecordModel;
use Game\Protobuf\CGEnterScene;
use Game\Protobuf\GCEnterSceneResult;
use Game\Protobuf\PacketId;

class EnterScene extends ControllerBase
{
    private GCEnterSceneResult $sendMessage;

    public function __construct()
    {
        $this->message = new CGEnterScene();
        $this->sendMessage = new GCEnterSceneResult();
    }

    public function run(): int
    {
        $joinId = $this->message->getJoinId();
        //校验
        /**
         * @var RecordModel $recordModel
         */
        $recordModel = ModelManager::getInstance()->getModel(ModelTypeDefine::RECORD);
        $record = $recordModel->getRecordByJoinId($joinId);
        if (is_null($record)) {
            $this->sendMessage->setCode(ClientErrorCode::PVP_MATCHING_DATA_NOT_FOUND);
            SendMessage::getInstance()->sendClient(PacketId::GC_EnterSceneResult, $this->sendMessage);
            return ErrorDefine::SUCCESS;
        }
        /**
         * @var PvpBaseModel $pvp
         */
        $pvp = ModelManager::getInstance()->getModel(ModelTypeDefine::PVP_BASE);
        if ($joinId != $record->joinId) {
            $this->sendMessage->setCode(ClientErrorCode::PVP_MATCHING_JOIN_ID_ERROR);
            SendMessage::getInstance()->sendClient(PacketId::GC_EnterSceneResult, $this->sendMessage);
            return ErrorDefine::SUCCESS;
        }
        //更新状态
        $pvp->updateStatus(GameConstantDefine::PLAYER_STATUS_GAMING);

        $this->sendMessage->setCode(ErrorDefine::SUCCESS);
        SendMessage::getInstance()->sendClient(PacketId::GC_EnterSceneResult, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}