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;
    private final Long workerId;
    private final Long datacenterId;
    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() {
        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();
        }
    }
}
