package com.yunfeiyun.agmp.common.framework.config;

import com.yunfeiyun.agmp.common.annotation.ConditionalRun;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseRunParam;
import com.yunfeiyun.agmp.common.core.domain.model.RunParam;
import com.yunfeiyun.agmp.common.utils.ConditionUtil;
import org.reflections.Reflections;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * 条件配置
 * 
 * @author 杨晓辉
 */
@Configuration
public class ConditionConfig
{

    public static final String  POST_CONSTRUCT = "post"; //post, after
    public static final String  PACKAGE_NAME = "com.yunfeiyun";
    /**
     * 	扫描项目包
     */
    @PostConstruct
    private void scanCondition() {
        ConditionConfig conditionConfig = new ConditionConfig();
        conditionConfig.runCondition();
    }
    public void runCondition() {
        Reflections reflections = new Reflections(PACKAGE_NAME);
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Component.class);
        for (Class clazz : typesAnnotatedWith) {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(ConditionalRun.class)) {
                    ConditionalRun baseCondition = method.getAnnotation(ConditionalRun.class);
                    if (null != baseCondition.level() && POST_CONSTRUCT.equals(baseCondition.level())) {
                        try {
                           if(ConditionUtil.matches( baseCondition )){
                               IBaseRunParam param = RunParam.build(baseCondition.level(),baseCondition.name(),baseCondition.key(),baseCondition.value());
                               method.invoke(clazz.newInstance(), param);
                           }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }
}
