<?php

/***
 * 取消匹配
 */

namespace Game\Model\Pvp;

use Framework\Log\LogMark;
use Framework\MVC\ModelManager;
use Framework\Logic\PacketCacheLogic;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Model\RecordModel;
use Game\Model\RoomModel;
use Game\Protobuf\GCCancelMatch;
use Game\Protobuf\PacketId;

class PacketRaceCancelMatch
{
    public int $playerId;

    use PacketCacheLogic;

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

    //删除比赛记录,返回roomId
    public function dealCancelMatching(int $code, int $joinID): ?int
    {
        /**
         * @var RecordModel $recordModel
         */
        $recordModel = ModelManager::getInstance()->getModel(ModelTypeDefine::RECORD);
        $record = $recordModel->getRecordByJoinId($joinID, $this->playerId);
        if (is_null($record)) {
            LogMark::getInstance()->markDebug(
                "[PVPFlowLog][PacketRaceCancelMatch] not found Record data",
                array(
                    "playerId" => $this->playerId,
                    "JoinId" => $joinID
                )
            );
            return null;
        }
        if(!$record->delRecord()) {
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_DELETE_ERROR,
                '[PVPFlowLog][PacketRaceCancelMatch] cancel match del record error!'
            );
            return null;
        }
        //发送取消匹配消息
        $this->sendCancelMessage($code, $joinID);
        LogMark::getInstance()->markInfo(
            "[PVPFlowLog][45][PacketRaceCancelMatch] send to client success"
        );
        return $record->roomID;
    }

    private function sendCancelMessage(int $code, int $joinId)
    {
        $sendMessage = new GCCancelMatch();
        $sendMessage->setCode($code);
        $sendMessage->setJoinID($joinId);
        $this->addPacket(PacketId::GC_CancelMatch, $sendMessage, $this->playerId);
    }

    public function changeRoomState(int $roomID): bool
    {
        /**
         * @var RoomModel $roomModel
         */
        $roomModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ROOM);
        $room = $roomModel->newRoom($roomID);
        if(!$room->searchRoomByRoomID()) {
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_UPDATE_ERROR,
                '[PacketRaceCancelMatch] cancel match search room error!', (array)$room
            );
            return false;
        }
        $room->setPlayType(RoomModel::ROOM_GAME_READY);
        if(!$room->saveDB()) {
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_UPDATE_ERROR,
                '[PacketRaceCancelMatch] cancel match save room error!', (array)$room
            );
            return false;
        }
        return true;
    }
}
