<?php

/**
 * ServerManager.php
 * 文件描述
 * Created On 2022/4/25
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Server;

use Server\Model\IServerBase;
use Server\Config\ServerConfig;
use Library\Common\Singletons;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;

class ServerManager
{
    use Singletons;

    protected array $modelList = array();

    public function init()
    {
        foreach (ServerConfig::MODEL_MAP as $k => $path) {
            $model = $this->createModel($path);
            if ($model == null) {
                LogMark::getInstance()->markCritical(
                    ErrorDefine::MODEL_CREATE_FAIL,
                    "create model fail",
                    array("modelType" => $k)
                );
                continue;
            }
            if ($model->init() == false) {
                LogMark::getInstance()->markCritical(
                    ErrorDefine::MODEL_CREATE_FAIL,
                    "model init fail",
                    array("modelType" => $k)
                );
                continue;
            }
            $this->modelList[$k] = $model;
        }
        return ErrorDefine::SUCCESS;
    }

    public function close()
    {
        /**
         * @var $model IServerBase
         */
        foreach ($this->modelList as $model) {
            $model->close();
        }
    }

    public function run($nowTime)
    {
        /**
         * @var $model IServerBase
         */
        foreach ($this->modelList as $model) {
            $model->run($nowTime);
        }
    }

    protected function createModel($path): ?IServerBase
    {
        $model = new $path();
        if ($model == null) {
            return null;
        }
        /*
        if (!is_subclass_of($model, 'IServerBase')) {
            return null;
        }
        */
        return  $model;
    }
}
