package com.topsunit.query.spring.mapper;

import com.topsunit.query.annotations.Mapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;

/**
 * @author yonghuan
 */
public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor {

    private String sqlExecutorBeanName;
    private final Class<? extends Annotation> annotationClass = Mapper.class;
    private String basePackage;
    private Class<? extends MapperFactoryBean> mapperFactoryBeanClass;

    public String getSqlExecutorBeanName() {
        return sqlExecutorBeanName;
    }

    public void setSqlExecutorBeanName(String sqlExecutorBeanName) {
        this.sqlExecutorBeanName = sqlExecutorBeanName;
    }

    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public Class<? extends MapperFactoryBean> getMapperFactoryBeanClass() {
        return mapperFactoryBeanClass;
    }

    public void setMapperFactoryBeanClass(Class<? extends MapperFactoryBean> mapperFactoryBeanClass) {
        this.mapperFactoryBeanClass = mapperFactoryBeanClass;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
        scanner.setSqlExecutorBeanName(sqlExecutorBeanName);
        scanner.setAnnotationClass(annotationClass);
        scanner.setMapperFactoryBeanClass(mapperFactoryBeanClass);
        scanner.registerFilters();
        scanner.scan(StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
