package com.mosty.wzzx.config.Listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.IndexResolver;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class ApplicationEventListener implements ApplicationListener {

    @Resource(name = "mostyMongoTemplate")
    protected MongoTemplate adminMongoTemplate;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof ContextClosedEvent) {
            //监听应用关闭
        }
    }

    @EventListener(ContextRefreshedEvent.class)
    public void initIndicesAfterStartup() {
        createIndex(adminMongoTemplate);
    }

    private void createIndex(MongoTemplate template) {
        MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = template
                .getConverter().getMappingContext();

        IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);
        // consider only entities that are annotated with @Document
        mappingContext.getPersistentEntities()
                .stream()
                .filter(it -> it.isAnnotationPresent(Document.class))
                .forEach(it -> {
                    try {
                        IndexOperations indexOps = template.indexOps(it.getType());
                        resolver.resolveIndexFor(it.getType()).forEach(indexOps::ensureIndex);
                    }catch (Exception e){
                        log.error("创建索引Ex:{}", e.getMessage());
                    }
                });
    }


}