package com.team5.aLife.BaseStation;

import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;

	public class MQTTConnection implements MqttSimpleCallback {
		
		static final String MQTT_PORT = "1883";
		
		IMqttClient mqttClient = null;
		
		public MQTTConnection(String hostName, String topic) throws MqttException {
			
			// make the connection specifications
			String connectionSpec = "tcp://" + hostName + "@" + MQTT_PORT;
			
			// Create and connect to the RSMB
			mqttClient = MqttClient.createMqttClient(connectionSpec, null);
			String clientID = "aLifeServer";
			
			// (clientID, Clean Start, Keep alive (seconds)
			mqttClient.connect(clientID, true, (short) 60);
			
		}
		
		public void disconnect(){
			try {
				mqttClient.disconnect();
			} catch (MqttPersistenceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public void publishToTopic (String topicName, String message) throws MqttException {
			if ((mqttClient == null) || !mqttClient.isConnected()){
				System.out.println("No connection");
			} else {
				// (topic name, length, QoS, Retain)
				mqttClient.publish(topicName, message.getBytes(), 0, false);
			}
		}

		@Override
		public void connectionLost() throws Exception {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void publishArrived(String arg0, byte[] arg1, int arg2,
				boolean arg3) throws Exception {
			// TODO Auto-generated method stub
			
		}
		
	}

