package com.izouma.nineth.config;

import com.izouma.nineth.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
@Slf4j
public class SnowflakeIdWorkerConfig {
    @Bean
    public SnowflakeIdWorker snowflakeIdWorker(GeneralProperties generalProperties) {
        int workerId = generalProperties.getWorkerId();
        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            Matcher matcher = Pattern.compile("raex-server-(?<num>\\d{3})").matcher(hostName);
            if (matcher.matches()) {
                workerId = Integer.parseInt(matcher.group("num"));
            }
        } catch (Exception e) {
        }
        log.info("init snowflakeIdWorker worker={} dataCenter={}", workerId, generalProperties.getDataCenterId());
        return new SnowflakeIdWorker(workerId, generalProperties.getDataCenterId());
    }
}
