package com.dji.sdk.mqtt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author sean.zhou
 * @date 2021/11/10
 * @version 0.1
 */
@Component
public class MqttTopicServiceImpl implements IMqttTopicService {

    private static final Logger log = LoggerFactory.getLogger(MqttTopicServiceImpl.class);

    @Resource
    private MqttPahoMessageDrivenChannelAdapter adapter;

    @Override
    public void subscribe(String... topics) {
        Set<String> topicSet = new HashSet<>(Arrays.asList(getSubscribedTopic()));
        for (String topic : topics) {
            if (topicSet.contains(topic) || isCoveredByWildcard(topicSet, topic)) {
                continue;
            }
            subscribe(topic, 1);
        }
    }

    @Override
    public void subscribe(String topic, int qos) {
        Set<String> topicSet = new HashSet<>(Arrays.asList(getSubscribedTopic()));
        if (topicSet.contains(topic) || isCoveredByWildcard(topicSet, topic)) {
            return;
        }
        log.debug("subscribe topic: {}", topic);
        adapter.addTopic(topic, qos);
    }

    @Override
    public void unsubscribe(String... topics) {
        Set<String> currentTopics = new HashSet<>(Arrays.asList(getSubscribedTopic()));
        for (String topic : topics) {
            if (!currentTopics.contains(topic)) {
                continue;
            }
            if (isCoveredByWildcard(currentTopics, topic)) {
                log.debug("skip unsubscribe, topic {} is covered by wildcard", topic);
                continue;
            }
            log.debug("unsubscribe topic: {}", topic);
            adapter.removeTopic(topic);
        }
    }

    public String[] getSubscribedTopic() {
        return adapter.getTopic();
    }

    /**
     * Check if a specific topic is already covered by a single-level wildcard (+) subscription.
     * e.g. "thing/product/DRONE-001/osd" is covered by "thing/product/+/osd"
     */
    private boolean isCoveredByWildcard(Set<String> existingTopics, String topic) {
        String[] parts = topic.split("/");
        if (parts.length < 3) {
            return false;
        }
        for (int i = 0; i < parts.length; i++) {
            String[] wildcardParts = parts.clone();
            wildcardParts[i] = "+";
            String wildcardTopic = String.join("/", wildcardParts);
            if (existingTopics.contains(wildcardTopic)) {
                return true;
            }
        }
        return false;
    }
}
