package cn.ibizlab.core.util.config;

import cn.ibizlab.core.data.mongodb.DynamicMongoContextHolder;
import cn.ibizlab.core.data.mongodb.DynamicMongoTemplate;
import cn.ibizlab.util.helper.JSR310DateConverters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Configuration
public class MongoDBConfig {

    @Value("${spring.data.mongodb.uri:mongodb://localhost:27017/admin}")
    private  String uri;



    @Bean
    public MongoCustomConversions customConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(JSR310DateConverters.DateToZonedDateTimeConverter.INSTANCE);
        converterList.add(JSR310DateConverters.ZonedDateTimeToDateConverter.INSTANCE);
        converterList.add(JSR310DateConverters.DurationToLongConverter.INSTANCE);
        converterList.add(JSR310DateConverters.TimestampToDateConverter.INSTANCE);
        converterList.add(JSR310DateConverters.DateToTimestampConverter.INSTANCE);
        return new MongoCustomConversions(converterList);
    }

    @Bean(name = "mongoTemplate")
    @Lazy
    public DynamicMongoTemplate mongoTemplate() {
        if(DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.size()==0)
            DynamicMongoContextHolder.addFactory("master",uri);
        Iterator<MongoDbFactory> iterator = DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
        return new DynamicMongoTemplate(iterator.next());
    }

    @Bean(name = "mongoDbFactory")
    @Lazy
    public MongoDbFactory mongoDbFactory() {
        Iterator<MongoDbFactory> iterator = DynamicMongoContextHolder.MONGO_CLIENT_DB_FACTORY_MAP.values().iterator();
        return iterator.next();
    }

}