<?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\ModelTypeDefine;
use Game\Logic\Room\RoomInfoLogic;
use Game\Model\Pvp\PvpBaseModel;
use Game\Protobuf\CGPvpJoinMatching;
use Game\Protobuf\GCPVPJoinMatching;
use Game\Protobuf\PacketId;

class JoinMatching extends ControllerBase
{
    use RoomInfoLogic;

    private GCPVPJoinMatching $sendMessage;

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

    public function run(): int
    {
        $roomID = $this->message->getRoomID();
        $roomType = $this->message->getRoomType();
        /**
         * @var PvpBaseModel $pvp
         */
        $pvp = ModelManager::getInstance()->getModel(ModelTypeDefine::PVP_BASE);

        //加入匹配
        if(empty($roomType)) {
            // 房间匹配
            [$code, $joinId] = $pvp->joinMatching($roomID);
            if ($code != ClientErrorCode::CLIENT_SUCCESS) {
                //匹配失败,修改房间内玩家状态
                $this->changeRoomPlayerToReady($roomID);
            }
        } else {
            // 自定义房间匹配
            [$code, $joinId] = $pvp->joinCustomizeRoomMatching($roomID);
        }
        $this->sendMessage->setJoinId($joinId);
        $this->sendMessage->setCode($code);
        SendMessage::getInstance()->sendClient(PacketId::GC_PVPJoinMatching, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}