package cn.axzo.workflow.starter.mq.broadcast.filter;

import cn.axzo.workflow.starter.WorkflowEngineStarterProperties;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static cn.axzo.workflow.common.constant.BpmnConstants.MQ_OWNERSHIP_PROCESS_DEFINITION_KEY;

/**
 * TODO
 *
 * @author wangli
 * @since 2024/6/4 17:06
 */
public class InnerFilterDefinitionKeyInner implements InnerMessageQueueHandleBeforeFilter {
    private final Logger log = LoggerFactory.getLogger(InnerFilterDefinitionKeyInner.class);
    private final WorkflowEngineStarterProperties properties;

    public InnerFilterDefinitionKeyInner(WorkflowEngineStarterProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean doFilter(MessageExt message) {
        if (!properties.getBroadcast().getEnableFilterDefinitionKey()) {
            return false;
        }
        if (CollectionUtils.isEmpty(properties.getBroadcast().getFilterProcessDefinitionKeys())) {
            log.warn("Your system has the filter process-definition-key enabled, but `BroadcastListenerConfigurationProperties.filterProcessDefinitionKeys` is empty");
            return false;
        }
        Map<String, String> headers = message.getProperties();
        String processDefinitionKey = headers.getOrDefault(MQ_OWNERSHIP_PROCESS_DEFINITION_KEY, "");
        if (properties.getBroadcast().getFilterProcessDefinitionKeys().contains(processDefinitionKey)) {
            return false;
        }
        log.info("The broadcast message does not belong to the key of interest, will be ignored. messageId: {}, message process-definition-key: {}", message.getMsgId(), processDefinitionKey);
        return true;
    }
}
