package com.usky.common.core.util.id;

import com.google.common.collect.Maps;

import java.util.concurrent.ConcurrentMap;

import static com.usky.common.core.util.id.IdWorkerTypeEnum.SNOWFLAKE;

/**
 * <p>分布式 ID 生成器容器</p>
 *
 * @author chenpeng
 * Create at February 12, 2019 at 11:56:08 GMT+8
 */
public final class IdWorkerContainer {

    private static final String WORKERS_KEY_SEPARATOR = "_";

    private static final ConcurrentMap<String, IdWorker> WORKERS = Maps.newConcurrentMap();

    private Long workerId;

    public IdWorkerContainer(Long workerId) {
        this.workerId = workerId;
    }

    /**
     * <p>获取给定 dataCenterId 对应的派号器，默认雪花</p>
     *
     * @param dataCenterId 数据中心 id
     * @return SnowflakeIdWorker
     * @author chenpeng
     * Create at February 12, 2019 at 13:16:50 GMT+8
     * @see IdWorker
     */
    public IdWorker getIdWorker(Long dataCenterId) {
        return getIdWorker(dataCenterId, SNOWFLAKE);
    }

    /**
     * <p>根据给定 dataCenterId 和类型获取对应的派号器，默认雪花</p>
     *
     * @param dataCenterId
     * @param idWorkerType
     * @return IdWorker
     * @author chenpeng
     * Create at February 12, 2019 at 13:38:10 GMT+8
     * @see IdWorker
     */
    public IdWorker getIdWorker(Long dataCenterId, IdWorkerTypeEnum idWorkerType) {

        IdWorker idWorker = null;

        if (idWorkerType == null) {
            idWorkerType = SNOWFLAKE;
        }

        if (dataCenterId != null) {
            IdWorker target = createIdWorker(dataCenterId, idWorkerType);
            if (target != null) {
                WORKERS.putIfAbsent(idWorkerType.name() + WORKERS_KEY_SEPARATOR + dataCenterId,
                        target);
                idWorker = target;
            }
        }

        return idWorker;
    }

    private IdWorker createIdWorker(Long dataCenterId, IdWorkerTypeEnum idWorkerType) {
        IdWorker idWorker = null;
        if (idWorkerType == SNOWFLAKE) {
            idWorker = new SnowflakeIdWorker(dataCenterId, workerId);
        }
        return idWorker;
    }
}
