package com.njzscloud.common.sn.support;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.core.ienum.Dict;
import com.njzscloud.common.sn.SnConfigService;
import com.njzscloud.common.sn.contant.SnSection;

import java.util.HashMap;
import java.util.Map;

public final class SnUtil {

    private static final SnConfigService SN_CONFIG_SERVICE = SpringUtil.getBean(SnConfigService.class);
    private static final Map<SnSection, Class<? extends SectionConfig>> SECTIONS = new HashMap<>();

    static {
        SECTIONS.put(SnSection.GuDing, FixedSectionConfig.class);
        SECTIONS.put(SnSection.ShiJian, TimeSectionConfig.class);
        SECTIONS.put(SnSection.ZiZeng, IncSectionConfig.class);
        SECTIONS.put(SnSection.SuiJi, RandomSectionConfig.class);
    }

    public static SectionConfig resolve(Map<String, Object> config) {
        String sectionName = MapUtil.getStr(config, "sectionName");
        Class<? extends SectionConfig> sectionClass = SECTIONS.get(Dict.parse(sectionName, SnSection.values()));
        SectionConfig sectionConfig;
        try {
            sectionConfig = sectionClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw Exceptions.error("配置解析失败");
        }
        sectionConfig.resolve(config);
        return sectionConfig;
    }

    public static String next() {
        return next("Default");
    }

    public static String next(String sncode) {
        return next(sncode, null);
    }

    public static synchronized String next(String sncode, String pici) {
        Assert.notBlank(sncode, () -> Exceptions.clierr("未指定编码规则"));
        return SN_CONFIG_SERVICE.getSn(sncode).next(pici);
    }
}
