<?php

/**
 * 初始RoleId
 */

namespace Tool\InitServer\Logic;

use Framework\DB\Handler\CommonDBHandler;
use Framework\Lib\Utils;
use Game\Config\GameConfig;
use Game\Constant\DBTableDefine;
use Game\Constant\GameConstantDefine;
use Game\Logic\CommonConstLogic;
use Tool\InitServer\Config;
use Tool\InitServer\IBase;

class InitRoleIds extends IBase
{
    use CommonConstLogic;
    use CommonDBHandler;

    protected function run(): bool
    {
        //查找当前生成的版本号
        $commonConstData = $this->getCommonConstData();
        $version = $commonConstData[GameConstantDefine::COMMON_KEY_ROLE_ID_VERSION] ?? 0;
        if (GameConfig::getInstance()->ROLE_ID_VERSION() > $version) {
            //防止重复生成id
            foreach ($this->generateIds() as $id)
            {
                $this->insQueueRPushCommon(
                    DBTableDefine::TABLE_COMMON_ROLES_ID,
                    0,
                    $id
                );
            }
            $this->saveCommonConstData(
                array(
                    GameConstantDefine::COMMON_KEY_ROLE_ID_VERSION => GameConfig::getInstance()->ROLE_ID_VERSION()
                )
            );
            echo "InitRoleIds success!";
            echo "<br>\n";
            return true;
        }
        echo "now roleId DB version is:{$version}, GameConfig version is:". GameConfig::getInstance()->ROLE_ID_VERSION(). "can not generate role id";
        echo "<br>\n";
        return true;
    }

    private function generateIds()
    {
        for ($i = 1; $i <= Config::ROLE_ID_NUM; $i++)
        {
            yield Utils::uniqueRoleId(GameConfig::getInstance()->SERVER_ID(), GameConfig::getInstance()->ROLE_ID_VERSION(), $i);
        }
    }
}
