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

import cn.axzo.workflow.starter.BroadcastListenerProperties;
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 static cn.axzo.workflow.common.constant.BpmnConstants.MQ_OWNERSHIP_APPLICATION;

/**
 * 对 {@link BroadcastListenerProperties#filterApplicationNames} 的实现
 *
 * @author wangli
 * @since 2024/6/4 17:06
 */
public class InnerFilterMQOwnerShip implements InnerMessageQueueHandleBeforeFilter {
    private final Logger log = LoggerFactory.getLogger(InnerFilterMQOwnerShip.class);

    private final WorkflowEngineStarterProperties properties;

    public InnerFilterMQOwnerShip(WorkflowEngineStarterProperties properties, String applicationName) {
        this.properties = properties;
        this.properties.getBroadcast().getFilterApplicationNames().add(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)) {
            log.debug("【{}】The broadcast message does not attribute the message, will not be ignored. messageId: {}", this.getClass().getSimpleName(), message.getMsgId());
            return false;
        } else {
            if (properties.getBroadcast().getFilterApplicationNames().contains(mqOwnerShip)) {
                return false;
            } else {
                log.debug("【{}】The broadcast message does not attribute the message, will be ignored. messageId: {}, mq-ownership-application: {}", this.getClass().getSimpleName(), message.getMsgId(), mqOwnerShip);
                return true;
            }
        }
    }
}
