package xiaoqu.home.open.mqtt;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MqttPushClient {
	private static final Logger log = Logger.getLogger("task");

	@Autowired
	private PushCallback pushCallback;

	private static MqttClient client;

	public MqttClient getClient() {
		return client;
	}

	private static void setClient(MqttClient client) {
		MqttPushClient.client = client;
	}

	public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) {
		try {
			MqttClient client = new MqttClient(host, clientID+"_"+System.nanoTime(), (MqttClientPersistence) new MemoryPersistence());
			MqttConnectOptions options = new MqttConnectOptions();
			options.setCleanSession(true);
			options.setUserName(username);
			options.setPassword(password.toCharArray());
			options.setConnectionTimeout(timeout);
			options.setKeepAliveInterval(keepalive);
			options.setAutomaticReconnect(true);
			setClient(client);
			try {
				client.setCallback((MqttCallback) this.pushCallback);
				client.connect(options);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void publish(int qos, boolean retained, String topic, String pushMessage) {
		MqttMessage message = new MqttMessage();
		message.setQos(qos);
		message.setRetained(retained);
		message.setPayload(pushMessage.getBytes());
		MqttTopic mTopic = getClient().getTopic(topic);
		if (mTopic == null) {
			log.error("topic not exist");
		}

		try {
			MqttDeliveryToken token = mTopic.publish(message);
			token.waitForCompletion();
		} catch (MqttPersistenceException e) {
			e.printStackTrace();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	public void subscribe(String topic, int qos) {
		log.info("开始订阅主题->" + topic);
		try {
			getClient().subscribe(topic, qos);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
}
