package com.lutao.cloud.iot.mqtt.core.util;

import com.lutao.cloud.iot.mqtt.codec.MqttCodecUtil;

import java.util.regex.Pattern;

/**
 * Mqtt Topic 工具
 */
public final class MqttTopicUtil {

    /**
     * 判断 topicFilter topicName 是否匹配
     *
     * @param topicFilter topicFilter
     * @param topicName   topicName
     * @return 是否匹配
     */
    public static boolean match(String topicFilter, String topicName) {
        if (MqttCodecUtil.isTopicFilter(topicFilter)) {
            return getTopicPattern(topicFilter).matcher(topicName).matches();
        } else {
            return topicFilter.equals(topicName);
        }
    }

    /**
     * mqtt topicFilter 转正则
     *
     * @param topicFilter topicFilter
     * @return Pattern
     */
    public static Pattern getTopicPattern(String topicFilter) {
        // mqtt 分享主题 $share/{ShareName}/{filter}
        String topicRegex = topicFilter.startsWith("$") ? "\\" + topicFilter : topicFilter;
        return Pattern.compile(topicRegex
                .replace("+", "[^/]+")
                .replace("#", ".+")
                .concat("$")
        );
    }

}

