<?php
/**
 * 房间检测，如果房间内玩家是离线，则帮助玩家退出房间
 * @date 2022-5-19
 * @author leeFx
 **/
namespace Server\Model\Player;

use Framework\Lib\Utils;
use Game\Constant\GameConstantDefine;
use Server\Model\IServerBase;
use Framework\Log\LogMark;
use Game\Constant\GameErrorCode;
use Game\Logic\Room\RoomLogic;
use Game\Model\RoomModel;

class CheckRoom implements IServerBase
{
    use RoomLogic;

    public function init(): bool
    {
        LogMark::getInstance()->markInfo("check time out room init success!");
        return true;
    }

    public function close()
    {
        // TODO: Implement close() method.
    }

    public function run($nowTime)
    {
        if (!$this->cliGetTimeOutRoomList($ret)){
            return false;
        }
        if (is_array($ret) && count($ret) > 0){
            foreach ($ret as $roomID => $time){
                if (Utils::getServerTimestamp() - $time > RoomModel::CHECK_ROOM_TIME){
                    // 获取room内玩家信息
                    $room = $this->cliGetRoomInfoByRoomID($roomID);
                    if(is_null($room)) {
                        continue;
                    }
                    $players = $room->playerInfo;
                    if(empty($players)) {
                        continue;
                    }
                    LogMark::getInstance()->markDebug(
                        "[CheckRoom] CLI over time room",
                        (array)$room
                    );
                    foreach ($players as $playerID => $data) {
                        // 检测玩家在线状态
                        if ($this->getRoleStatus($playerID) != GameConstantDefine::PLAYER_STATUS_OFFLINE){
                            continue;
                        }
                        // 离线则退出房间操作
                        LogMark::getInstance()->markInfo(
                            "offline exit room exec!",
                            ['roomID' => $roomID, 'playerID' => $playerID]
                        );
                        if(!$this->cliCheckOffLineExitRoom($roomID, $playerID)) {
                            LogMark::getInstance()->markError(
                                GameErrorCode::DATA_DELETE_ERROR,
                                '[roomModel] cli check exit room error!',
                                ['roomID' => $roomID, 'playerID' => $playerID]
                            );
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}