package com.njzscloud.common.sn.support;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.core.ienum.Dict;
import com.njzscloud.common.sn.contant.RandomMode;
import com.njzscloud.common.sn.contant.SnSection;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.util.Map;

@Getter
@Setter
@ToString
@Accessors(chain = true)
public class RandomSectionConfig implements SectionConfig {
    private final SnSection sectionName = SnSection.SuiJi;
    private RandomMode randomMode;
    private Long workerId;
    private Long datacenterId;
    private Integer nanoIdSize;

    @Override
    public ISnSection section() {
        return new RandomSection(randomMode, workerId, datacenterId, nanoIdSize);
    }

    @Override
    public void resolve(Map<String, Object> config) {
        randomMode = Dict.parse(MapUtil.getStr(config, "randomMode"), RandomMode.values());
        workerId = MapUtil.getLong(config, "workerId");
        datacenterId = MapUtil.getLong(config, "datacenterId");
        nanoIdSize = MapUtil.getInt(config, "nanoIdSize");
        Assert.notNull(randomMode, () -> Exceptions.clierr("随机编码配置错误，未设置字段 randomMode"));
        if (randomMode == RandomMode.NanoId) {
            Assert.notNull(nanoIdSize, () -> Exceptions.clierr("随机编码配置错误，未设置字段 nanoIdSize"));
            Assert.isNull(workerId, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 workerId"));
            Assert.isNull(datacenterId, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 datacenterId"));
        } else if (randomMode == RandomMode.SnowFlake) {
            Assert.notNull(workerId, () -> Exceptions.clierr("随机编码配置错误，未设置字段 workerId"));
            Assert.notNull(datacenterId, () -> Exceptions.clierr("随机编码配置错误，未设置字段 datacenterId"));
            Assert.isNull(nanoIdSize, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 nanoIdSize"));
        } else {
            Assert.isNull(workerId, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 workerId"));
            Assert.isNull(datacenterId, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 datacenterId"));
            Assert.isNull(nanoIdSize, () -> Exceptions.clierr("随机编码配置错误，无需设置字段 nanoIdSize"));
        }
    }
}
