package at.procon.dip.runtime.condition;

import at.procon.dip.runtime.config.RuntimeMode;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

public class RuntimeModeCondition implements Condition, EnvironmentAware {

    private Environment environment;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnRuntimeMode.class.getName());
        if (attributes == null || !attributes.containsKey("value")) {
            return false;
        }

        RuntimeMode expected = (RuntimeMode) attributes.get("value");
        String configured = context.getEnvironment().getProperty("dip.runtime.mode", RuntimeMode.LEGACY.name());
        RuntimeMode actual;
        try {
            actual = RuntimeMode.valueOf(configured.trim().toUpperCase());
        } catch (Exception ex) {
            actual = RuntimeMode.LEGACY;
        }
        return actual == expected;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
