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.StringUtils;

import java.util.Map;
import java.util.Objects;

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

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

    private final WorkflowEngineStarterProperties properties;
    private final String applicationName;

    public InnerFilterMQOwnerShipInner(WorkflowEngineStarterProperties properties, String applicationName) {
        this.properties = properties;
        this.applicationName = applicationName;
    }

    @Override
    public boolean doFilter(MessageExt message) {
        if (!properties.getBroadcast().getEnableFilterApplicationName()) {
            return false;
        }
        Map<String, String> headers = message.getProperties();
        String mqOwnerShip = headers.getOrDefault(MQ_OWNERSHIP_APPLICATION, null);
        if (StringUtils.hasText(mqOwnerShip) && Objects.equals(mqOwnerShip, applicationName)) {
            return false;
        }
        log.info("The broadcast message does not attribute the message, will be ignored. messageId: {}, mq-ownership-application: {}", message.getMsgId(), mqOwnerShip);
        return true;
    }
}
