package com.bcxin.Infrastructures;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Map;
import java.util.Random;

@Configuration
@ComponentScan({"com.bcxin.Infrastructures","com.bcxin.Infrastructures.components"})
@EnableConfigurationProperties(TenantConfigProperty.class)
public class InitConfig {
    private final Random workerRandom = new Random();

    public InitConfig(ApplicationContext beanFactory) {
        TenantContext.getInstance().setInjectResolver(new InjectResolver() {
            @Override
            public <T> T resolve(Class<T> tClass) {
                return beanFactory.getBean(tClass);
            }

            @Override
            public <T> Collection<T> resolveAll(Class<T> tClass) {
                Map<String, T> maps = beanFactory.getBeansOfType(tClass);

                return maps.values();
            }
        });
    }

    @Bean
    public IdWorker idWorker() {
        return new IdWorker.SnowflakeIdWorker(workerRandom.nextInt(31), workerRandom.nextInt(31));
    }
}
