<?php

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

namespace Framework\DB;

use Game\Constant\TestParams;
use Library\Common\Singletons;
use Framework\Define\DBDefine;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;

class DBManager
{
    use Singletons;

    private DBCondition $condition;

    private DBDefine $logic_config;

    private array $logic_handle;

    public function init(DBDefine $config)
    {
        $this->logic_config = $config;
        $this->condition = new DBCondition();
        $this->logic_handle = array();
    }

    public function executeRedis($logic_type, $table, $param, &$ret): bool
    {
        $this->condition->table_name = $table;
        $this->condition->logic_type = $logic_type;
        $this->condition->param = $param;
        $this->condition->exe_ret = "";
        $this->condition->exe_success = false;
        $logic = $this->getRedisDBLogic($logic_type);
        if (null == $logic) {
            LogMark::getInstance()->markCritical(
                ErrorDefine::REDIS_LOGIC_ERROR,
                "create redis db logic error",
                array("logicType" => $logic_type)
            );
            return false;
        }
        if (!$logic->checkParam($this->condition)) {
            return false;
        }
        $redis = DBContainer::getInstance()->getRedisByTable($table);
        if (null == $redis) {
            return false;
        }
        if($redis->ExistError()){
            LogMark::getInstance()->markCritical(
                ErrorDefine::REDIS_LOGIC_ERROR,
                " ss redis  error". $redis->getLastError());
            return false;
        }
        if (!$logic->execute($redis)) {
            return false;
        }

        if (!$logic->dealResult($ret)) {
            return false;
        }
        return true;
    }

    private function getRedisDBLogic($logic): ?DBLogicBase
    {
        if (array_key_exists($logic, $this->logic_handle)) {
            return $this->logic_handle[$logic];
        }
        $name = $this->logic_config->getDBLogicName($logic);
        if ("" == $name) {
            return null;
        }
        $logicObj = new $name();
        if ($logicObj == null) {
            return null;
        }
        $this->logic_handle[$logic] = $logicObj;
        return $logicObj;
    }
}
