package cn.axzo.workflow.starter.common.condition;

import cn.axzo.workflow.starter.WorkflowEngineStarterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

import java.util.Objects;

import static cn.axzo.workflow.starter.common.constant.StarterConstants.DEBUGGING_MQ_SUFFIX;
import static cn.axzo.workflow.starter.common.constant.StarterConstants.K8S_POD_NAME_SPACE;
import static cn.axzo.workflow.starter.common.constant.StarterConstants.MQ_GID_NAME_SEGMENT;
import static cn.axzo.workflow.starter.common.constant.StarterConstants.NACOS_PROFILES_ACTIVE;

/**
 * 用于处理 MQ 的消费者, 在本地启动或在容器中启动时, 能自主控制是否并入统一的消费组
 * <p>
 * 可查看 {@link WorkflowEngineStarterProperties#joinContainerGroup} 属性, 来了解本类的用途,
 * 特别需要注意的是: Starter 是结合 K8S 的命名空间(namespace) 来处理的.
 *
 * @author wangli
 * @since 2024/5/30 22:19
 */
public class NonContainerEnvironmentCondition implements Condition {

    private static final Logger log = LoggerFactory.getLogger(NonContainerEnvironmentCondition.class);

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
        String myPodNamespace = environment.getProperty(K8S_POD_NAME_SPACE);
        String activeProfile = environment.getProperty(NACOS_PROFILES_ACTIVE);
        if (!StringUtils.hasText(activeProfile)) {
            activeProfile = environment.getProperty("spring.profiles.active", String.class);
        }
        // 在容器环境时, 强制加入集群消费组
        if (StringUtils.hasText(myPodNamespace)) {
            environment.getSystemProperties().put(MQ_GID_NAME_SEGMENT, activeProfile);
            return true;
        }

        // 优先外部化配置
        Boolean joinContainerGroup = environment.getProperty("workflow.engine.starter.join-container-group", Boolean.class);
        if (Objects.isNull(joinContainerGroup)) {
            // 获取默认值
            joinContainerGroup = new WorkflowEngineStarterProperties().getJoinContainerGroup();
        }
        log.debug("workflow engine starter join-container-group status: {} ", joinContainerGroup);

        environment.getSystemProperties().put(MQ_GID_NAME_SEGMENT,
                joinContainerGroup ? activeProfile : activeProfile + DEBUGGING_MQ_SUFFIX);

        return true;
    }

}
