package com.njzscloud.common.core.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.ex.Exceptions;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

/**
 * <p>缓存/Redis 等 Key</p>
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class Key {
    private final String keyTpl;

    /**
     * <p>创建 KEY</p>
     * <p>KEY 字符串模板：可用：{名称} 做为占位符</p>
     *
     * @param keyTpl KEY 字符串模板
     * @return KEY 对象
     */
    public static Key create(String keyTpl) {
        Assert.notEmpty(keyTpl, () -> Exceptions.error("KEY 字符串模板不能为空"));
        keyTpl = keyTpl.replaceAll("\\{\\w+}", "{}");
        return new Key(keyTpl);
    }

    /**
     * <p>填充 KEY 模板</p>
     *
     * @param params 填充参数
     * @return key 值
     */
    public String fill(Object... params) {
        int count = StrUtil.count(keyTpl, "{}");
        Assert.isTrue(count == params.length,
            () -> Exceptions.error("占位符数量：[{}]与参数数量：[{}]不一致", count, params.length));
        return StrUtil.format(keyTpl, params);
    }
}
