package com.wecloud.im.core.util;

import cn.hutool.core.lang.Snowflake;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * 雪花算法 获取id工具类
 *
 * @author
 */
@Component
public class SnowflakeUtil {

    /**
     * workerId, dataCenterId动态获取
     * 12位序列号部分，支持同一毫秒内同一个节点可以生成4096个ID,  在目前一段不用做成动态获取服务器ID
     */
    private static volatile Snowflake SNOWFLAKE = null;

    /**
     * 多线程中加synchronized 保证不会获取重复id
     *
     * @return
     */
    public static Long getId() {

        if (SNOWFLAKE == null) {
            synchronized (SnowflakeUtil.class) {
                if (SNOWFLAKE == null) {
                    SNOWFLAKE = new Snowflake(SnowflakeUtil.getWorkId(), 1L);
                }
            }
        }
        return SNOWFLAKE.nextId();
    }

    /**
     * workId通过本机ip计算获得
     * @return
     */
    private static Long getWorkId(){
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for(int b : ints){
                sums += b;
            }
            return (long)(sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0,31);
        }
    }

}
