<?php

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

namespace Framework\DB\DBLogic;

use Exception;
use Framework\DB\DBCondition;
use Framework\DB\DBLogicBase;
use Library\DB\IRedis;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;

class DBLogicRedisCommand extends DBLogicBase
{
    protected DBCondition $condition;

    protected string $result;

    protected string $cmd;

    protected array $cmdParam;

    public function checkParam(DBCondition $param): bool
    {
        $this->condition = $param;
        if (count($this->condition->param) < 2) {
            LogMark::getInstance()->markError(
                ErrorDefine::REDIS_COMMAND_PARAM_ERROR,
                "DBLogicRedisCommand check param num less 2",
                array("DBCondition" => json_encode($param))
            );
            return false;
        }
        $this->cmd = $this->condition->param[0];
        $this->cmdParam = array_slice($this->condition->param, 1);
        $this->result = "";
        return true;
    }

    public function execute(IRedis $redis): bool
    {
        $cmd = $this->cmd;
        if (!method_exists($redis, $cmd)) {
            LogMark::getInstance()->markError(
                ErrorDefine::REDIS_COMMAND_NOT_EXIST,
                "redis command not exist",
                array("cmd" => $cmd)
            );
            return false;
        }
        try {
            if (!$redis->$cmd($this->result, $this->cmdParam)) {
                $this->condition->exe_error = $redis->getLastError();
                LogMark::getInstance()->markError(
                    ErrorDefine::REDIS_COMMAND_RUN_FAIL,
                    "redis command run fail",
                    array("cmd" => $cmd,
                        "redisError" => $this->condition->exe_error,
                        "param" => json_encode($this->cmdParam))
                );

                return false;
            }
        } catch (Exception $e) {
            $this->condition->exe_error = $e->getMessage();
            LogMark::getInstance()->markError(
                ErrorDefine::REDIS_COMMAND_RUN_FAIL,
                "redis command run fail",
                array("cmd" => $cmd,
                    "redisError" => $this->condition->exe_error,
                    "param" => json_encode($this->cmdParam))
            );
            return false;
        }
        return true;
    }

    public function dealResult(&$des): bool
    {
        $des = $this->result;
        return true;
    }
}
