package cn.quantgroup.xyqb.config;

import cn.quantgroup.xyqb.util.DefaultSequencer;
import cn.quantgroup.xyqb.util.IdentitySequencer;
import cn.quantgroup.xyqb.util.ServerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * Created by hechao on 2020/1/22.
 */
@Configuration
@EnableConfigurationProperties
public class AutoConfiguration {

    @Autowired
    private Environment environment;

    @EnableConfigurationProperties
    class Sequencer {

        @Bean
        @ConditionalOnMissingBean
        public IdentitySequencer identitySequencer(SequencerProperties sequencerProperties) throws Exception {
            Integer integerPort = ServerUtils.getIntegerPort(environment);
            Long workId = null;
            if (integerPort != null) {
                workId = integerPort.longValue();
            }
            if (workId == null) {
                throw new IllegalArgumentException("server port is null.");
            }
            workId = ServerUtils.getLongHostAddress() ^ integerPort;
            return new DefaultSequencer(workId, sequencerProperties);
        }
    }
}