<?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\RoomData;
use Game\Logic\Room\RoomLogic;
use Game\Model\RoomCustomizeModel;
use Game\Protobuf\CGSyncChatID;
use Game\Protobuf\GCSyncChatID;
use Game\Protobuf\PacketId;

class SyncChatID extends ControllerBase {
    use RoomLogic;
    public GCSyncChatID $sendMessage;
    public function __construct() {
        $this->message = new CGSyncChatID();
        $this->sendMessage = new GCSyncChatID();
    }

    public function run(): int {
        $roomID = $this->message->getRoomID();
        $roomType = $this->message->getRoomType();
        $chatID = $this->message->getChatID();
        if(empty($roomType)) {
            $room = new RoomData($roomID);
            $room->searchRoomByRoomID();
            $room->chatID =  $chatID;
            $room->saveDB();
            foreach($room->playerInfo as $id => $p) {
                $this->sendMessage->setCode(ClientErrorCode::CLIENT_SUCCESS);
                $this->sendMessage->setChatID($chatID);
                $this->addPacket(PacketId::GC_SyncChatID, $this->sendMessage, $id);
            }
        } else {
            /**
             * @var RoomCustomizeModel $roomModel
             */
            $roomModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ROOM_CUSTOMIZE);
            $this->playerID = $roomModel->playerId;
            $room = $roomModel->newRoom($roomID);
            if(!$room->searchRoomByRoomID()) {
                LogMark::getInstance()->markError(
                    GameErrorCode::DATA_UPDATE_ERROR,
                    '[sync chat id] chat id sync customize room search  error!', (array)$room
                );
            }
            $room->chatID =  $chatID;
            $room->saveDB();
            foreach($room->playerInfo as $id => $p) {
                $this->sendMessage->setCode(ClientErrorCode::CLIENT_SUCCESS);
                $this->sendMessage->setChatID($chatID);
                $this->addPacket(PacketId::GC_SyncChatID, $this->sendMessage, $id);
            }
        }
        return ErrorDefine::SUCCESS;
    }
}