package com.trade.common.annotation;

import java.util.ArrayList;
import java.util.List;

import com.trade.common.core.domain.BaseI18nEntity;
import com.trade.common.utils.I18nUtil;
import com.trade.common.utils.ReflectionUtil;
import org.apache.ibatis.io.VFS;
import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

public class I18nEntityScannerRegistrar implements ImportBeanDefinitionRegistrar {

    public static final Logger log = LoggerFactory.getLogger(I18nEntityScannerRegistrar.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annotationAttrs = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(I18nEntityScan.class.getName()));
        if (annotationAttrs == null) {
            return;
        }
        List<String> basePackages = new ArrayList<>();
        for (String pkg : annotationAttrs.getStringArray("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : annotationAttrs.getStringArray("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (Class<?> clazz : annotationAttrs.getClassArray("basePackageClasses")) {
            basePackages.add(ClassUtils.getPackageName(clazz));
        }
        if (CollectionUtils.isNotEmpty(basePackages)) {
            // 必须设置SpringBootVFS
            VFS.addImplClass(SpringBootVFS.class);
            // package缓存
            I18nUtil.i18nEntityMethodCache = ReflectionUtil.getReflectorsFromPackage(basePackages,
                    BaseI18nEntity.class);
        } else {
            log.info("I18nEntityScan is not configured,if not use i18n interceptor,that's ok!");
        }
    }
}
