<?php

/**
 * ModelManager.php
 * 文件描述
 * Created On 2022/1/19
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Framework\MVC;

use Framework\Define\ErrorDefine;
use Framework\Define\IModelDefine;
use Library\Common\Singletons;
use Framework\Log\LogMark;

class ModelManager
{
    use Singletons;

    private IModelDefine $modelDefine;

    private array $modelList;

    private int $playerId;

    public function init(IModelDefine $define)
    {
        $this->modelDefine = $define;
        $this->modelList = array();
    }

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

    public function clearModelList() {
        $this->modelList = [];
    }


    public function getModel($type)
    {
        if (array_key_exists($type, $this->modelList)) {
            return $this->modelList[$type];
        }
        $model_name = $this->modelDefine->getModelName($type);
        if ($model_name == "") {
            LogMark::getInstance()->markCritical(
                ErrorDefine::MODEL_CREATE_FAIL,
                "create model fail",
                array("modelType" => $type)
            );
            return null;
        }
        $model = new $model_name();
        if (method_exists($model, "setPlayerId")) {
            $model->setPlayerId($this->playerId);
        }
        $this->modelList[$type] = $model;
        return $model;
    }
}
