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

import cn.axzo.workflow.starter.handler.filter.global.BroadcastMessageQueueFilter;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.core.Ordered;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 用于扩展业务自己的 MQ 事件过滤器
 *
 * @author wangli
 * @since 2024/6/4 17:10
 */
public class InnerFilterExtension implements InnerMessageQueueHandleBeforeFilter {
    private final Logger log = LoggerFactory.getLogger(InnerFilterExtension.class);

    private final List<BroadcastMessageQueueFilter> businessFilters;

    public InnerFilterExtension(ObjectProvider<List<BroadcastMessageQueueFilter>> businessFilterProvider) {
        this.businessFilters = businessFilterProvider.getIfAvailable(Collections::emptyList)
                .stream().sorted(Comparator.comparing(Ordered::getOrder))
                .collect(Collectors.toList());
    }

    @Override
    public boolean doFilter(MessageExt message) {
        if (businessFilters.isEmpty()) {
            log.debug("【{}】business extension filter is empty", this.getClass().getSimpleName());
            return false;
        }
        for (BroadcastMessageQueueFilter businessFilter : businessFilters) {
            if (businessFilter.doFilter(message, new String(message.getBody(), UTF_8))) {
                return true;
            }
        }
        return false;
    }


    private Class<?> getParameterizedTypeClass(BroadcastMessageQueueFilter filter) {
        Type type = filter.getClass().getGenericInterfaces()[0];
        if (type instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
        return null;
    }

}
