package com.lutao.cloud.iot.mqtt.core.server.store;



import com.lutao.cloud.iot.mqtt.core.server.model.model.Message;
import com.lutao.cloud.iot.mqtt.core.util.MqttTopicUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;

/**
 * message store
 *

 */
public class InMemoryMqttMessageStore implements IMqttMessageStore {
	/**
	 * 遗嘱消息 clientId: Message
	 */
	private final ConcurrentMap<String, Message> willStore = new ConcurrentHashMap<>();
	/**
	 * 保持消息 topic: Message
	 */
	private final ConcurrentMap<String, Message> retainStore = new ConcurrentHashMap<>();

	@Override
	public boolean addWillMessage(String clientId, Message message) {
		willStore.put(clientId, message);
		return true;
	}

	@Override
	public boolean clearWillMessage(String clientId) {
		willStore.remove(clientId);
		return true;
	}

	@Override
	public Message getWillMessage(String clientId) {
		return willStore.get(clientId);
	}

	@Override
	public boolean addRetainMessage(String topic, Message message) {
		retainStore.put(topic, message);
		return true;
	}

	@Override
	public boolean clearRetainMessage(String topic) {
		retainStore.remove(topic);
		return true;
	}

	@Override
	public List<Message> getRetainMessage(String topicFilter) {
		Pattern topicPattern = MqttTopicUtil.getTopicPattern(topicFilter);
		List<Message> retainMessageList = new ArrayList<>();
		retainStore.forEach((topic, message) -> {
			if (topicPattern.matcher(topic).matches()) {
				retainMessageList.add(message);
			}
		});
		return retainMessageList;
	}

}
