<?php

/**
 * desc 房间内同步改装数据
 */

namespace Game\Controller\Room;

use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\MVC\ModelManager;
use Game\Constant\ClientErrorCode;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Data\AccountData;
use Game\Data\RoomData;
use Game\Logic\CarExteriorRefitLogic;
use Game\Logic\Room\RoomLogic;
use Game\Model\RoomCustomizeModel;
use Game\Protobuf\CGSyncRoomExteriorRefit;
use Game\Protobuf\GCSyncRoomExteriorRefit;
use Game\Protobuf\PacketId;

class SyncRoomExteriorRefit extends ControllerBase {

    use RoomLogic;
    use CarExteriorRefitLogic;
    private GCSyncRoomExteriorRefit $sendMessage;

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

    public function run(): int {
        $roomType = $this->message->getRoomType();
        $roomID = $this->message->getRoomID();
        switch ($roomType) {
            case 0:
                $room = new RoomData($roomID);
                break;
            case 1:
                /**
                 * @var RoomCustomizeModel $roomModel
                 */
                $roomModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ROOM_CUSTOMIZE);
                $this->playerID = $roomModel->playerId;
                $room = $roomModel->newRoom($roomID);
                break;
        }

        if(!$room->searchRoomByRoomID()) {
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_UPDATE_ERROR,
                '[sync room exterior refit] car exterior refit sync customize room search  error!', (array)$room
            );
        }
        $carUID = $this->getAccountAttribute(AccountData::DB_DEFAULT_CAR);
        $carExteriorRefit = $this->getCarExteriorRefitFormatData($carUID);
        $room->playerInfo[$this->playerId][RoomData::EXTERIOR_REFIT] =  $carExteriorRefit;
        $room->saveDB();

        $this->sendMessage->setRoomType($roomType);
        $this->sendMessage->setRoomID($roomID);
        $this->sendMessage->setPlayerID($this->playerId);
        $this->sendMessage->setExteriorRefit($carExteriorRefit);
        foreach($room->playerInfo as $id => $p) {
            $this->addPacket(PacketId::GC_SyncRoomExteriorRefit, $this->sendMessage, $id);
        }

        return ErrorDefine::SUCCESS;
    }
}