<?php

/**
 * 初始驾照排名
 */

namespace Tool\InitServer\Logic;

use Framework\DB\Handler\CommonDBHandler;
use Game\Constant\DBTableDefine;
use Tool\InitServer\IBase;

class InitDrivingLicenseRankId extends IBase
{
    use CommonDBHandler;

    private const DrivingLicenseRankId = "DrivingLicenseRankId"; //驾照id排名

    protected function run(): bool
    {
        $drivingLicenseRankId = "DrivingLicenseRankId";
        //检查是否已经存在
        $rankId = $this->getCommonConstValue($drivingLicenseRankId);
        if (is_null($rankId)) {
            return $this->initRankId();
        }
        //存在key 检查更新时间
        $lastDate = $this->getCommonConstValue("MapDate");
        if (is_null($lastDate)) {
            return $this->initRankId();
        }
        //检查时间是否和今天一致
        if (date("Y-m-d") == $lastDate) {
            //不更新排名
            $this->printResult("same date,don't update rankId,now rankId is {$rankId}");
            return true;
        }
        return $this->initRankId();
    }

    private function initRankId(): bool
    {
        //初始rankId
        if ($this->setCommonConstKey(self::DrivingLicenseRankId, 0)) {
            $this->printResult("InitDrivingLicenseRankId success!");
            return true;
        }
        $this->printResult("InitDrivingLicenseRankId Fail!");
        return false;
    }

    private function getCommonConstValue(string $key): ?string
    {
        $result = array();
        $this->searchCommonTitle(
            DBTableDefine::TABLE_COMMON_CONST,
            0,
            $result
        );
        return $result[$key] ?? null;
    }

    private function setCommonConstKey(string $key, string $value): bool
    {
        return $this->updateCommonTitle(
            DBTableDefine::TABLE_COMMON_CONST,
            0,
            array(
                $key => $value
            )
        );
    }

    private function printResult(string $msg)
    {
        echo $msg."<br>";
    }
}
