package com.yunfeiyun.agmp.common.utils;

import com.yunfeiyun.agmp.common.annotation.ConditionalRun;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.reflections.Reflections;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ConditionUtil {

    public static final String  POST_CONSTRUCT = "post"; //post, after
    public static final String  PACKAGE_NAME = "com.yunfeiyun";

    public static boolean matches(ConditionalRun annotation) {
        if (StringUtils.isNull(annotation)) {
            return true;
        }
        // 获取注解的属性值
        String level = annotation.level();
        String name = annotation.name();
        String[] keys =  annotation.key();
        String[] values =  annotation.value();
        Environment environment = SpringUtils.getApplicationContext().getEnvironment();
        return matches(keys, values, environment);
    }

    public static boolean matches(String[] keys, String[] values, Environment environment) {
        List<Boolean> matches = new ArrayList<Boolean>();
        for (int pos = 0; pos < keys.length; pos++) {
            // 通过环境变量拿到项目配置信息
            String property = environment.getProperty(keys[pos]);
            String value = values[pos];
            if (value != null && value.equals(property)) {
                matches.add(true);
            }else{
                matches.add(false);
            }
        }
        matches = matches.stream().filter(v-> v== false).collect(Collectors.toList());
        if(matches ==null || matches.size() > 0 ) return false;
        return true;
    }


    public static synchronized Method get() {
        Reflections reflections = new Reflections(PACKAGE_NAME);
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Component.class);
        for (Class clazz : typesAnnotatedWith) {
            Method[] methods = clazz.getDeclaredMethods();
            Method method = Arrays.stream(methods).filter(v->v.isAnnotationPresent(ConditionalRun.class)).findAny().orElse(null);
            return method;
        }
        return null;
    }
}
