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

import com.lutao.cloud.iot.mqtt.codec.MqttQoS;
import com.lutao.cloud.iot.mqtt.codec.MqttTopicSubscription;
import com.lutao.cloud.iot.mqtt.core.util.MqttTopicUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 发送订阅，未 ack 前的数据承载
 */
@Slf4j
public final class MqttClientSubscription implements Serializable {
    private final String topicFilter;
    private final MqttQoS mqttQoS;
    private final Pattern topicRegex;
    private final IMqttClientMessageListener listener;

    public MqttClientSubscription(MqttQoS mqttQoS,
                                  String topicFilter,
                                  IMqttClientMessageListener listener) {
        this.mqttQoS = Objects.requireNonNull(mqttQoS, "MQTT subscribe mqttQoS is null.");
        this.topicFilter = Objects.requireNonNull(topicFilter, "MQTT subscribe topicFilter is null.");
        this.topicRegex = MqttTopicUtil.getTopicPattern(topicFilter);
        this.listener = Objects.requireNonNull(listener, "MQTT subscribe listener is null.");
    }

    public MqttQoS getMqttQoS() {
        return mqttQoS;
    }

    public String getTopicFilter() {
        return topicFilter;
    }

    public IMqttClientMessageListener getListener() {
        return listener;
    }

    public boolean matches(String topic) {
        return this.topicRegex.matcher(topic).matches();
    }

    public MqttTopicSubscription toTopicSubscription() {
        return new MqttTopicSubscription(topicFilter, mqttQoS);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        MqttClientSubscription that = (MqttClientSubscription) o;
        return Objects.equals(topicFilter, that.topicFilter) &&
                mqttQoS == that.mqttQoS &&
                Objects.equals(listener, that.listener);
    }

    @Override
    public int hashCode() {
        return Objects.hash(topicFilter, mqttQoS, listener);
    }

    @Override
    public String toString() {
        return "MqttClientSubscription{" +
                "topicFilter='" + topicFilter + '\'' +
                ", mqttQoS=" + mqttQoS +
                ", topicRegex=" + topicRegex +
                '}';
    }

}
