package cn.iocoder.yudao.framework.snowflake.config;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
import cn.iocoder.yudao.framework.redis.helper.RedisHelper;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author zhaobiyan
 */
@Slf4j
@Configuration
@AutoConfigureAfter(YudaoRedisAutoConfiguration.class)
public class SnowFlakeConfiguration {

    @Resource
    private RedisHelper redisHelper;

    @Bean
    public SnowflakeGenerator snowflakeGenerator() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        log.info("snow flask configuration, host address:{}", hostAddress);
        String workId = redisHelper.get("snowflake:work:id:" + hostAddress);
        if (StringUtils.isBlank(workId)) {
            Long nextWorkId = redisHelper.incrBy("incr:work:id", 1);
            redisHelper.set("snowflake:work:id:" + hostAddress, String.valueOf(nextWorkId));
            workId = String.valueOf(nextWorkId);
        }
        return new SnowflakeGenerator(Long.parseLong(workId), 0);
    }

}
