package com.njzscloud.common.sn.support;

import cn.hutool.core.util.IdUtil;
import com.njzscloud.common.sn.contant.RandomMode;

public class RandomSection implements ISnSection {
    /**
     * 随机模式
     */
    private final RandomMode randomMode;
    /**
     * 雪花码-工作节点ID
     */
    private final Long workerId;
    /**
     * 雪花码-数据中心ID
     */
    private final Long datacenterId;
    /**
     * NanoId码-大小
     */
    private final Integer nanoIdSize;

    public RandomSection(RandomMode randomMode, Long workerId, Long datacenterId, Integer nanoIdSize) {
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.nanoIdSize = nanoIdSize;
        this.randomMode = randomMode;
    }

    public RandomSection(Long workerId, Long datacenterId) {
        this(RandomMode.SnowFlake, workerId, datacenterId, 21);
    }

    public RandomSection(Integer nanoIdSize) {
        this(RandomMode.NanoId, null, null, nanoIdSize);
    }

    public RandomSection() {
        this(RandomMode.UUID, null, null, null);
    }

    @Override
    public String next(String pici) {
        switch (randomMode) {
            case UUID:
                return IdUtil.simpleUUID();
            case NanoId:
                return nanoIdSize == null ? IdUtil.nanoId() : IdUtil.nanoId(nanoIdSize);
            default:
                return workerId == null || datacenterId == null ? IdUtil.getSnowflakeNextIdStr() : IdUtil.getSnowflake(workerId, datacenterId).nextIdStr();
        }
    }
}
