package se.sics.sse.fresta.mqtt;

import android.util.Log;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.net.Socket;
import java.util.Observable;

public class MqttSubPub extends Observable implements MqttCallback{


     private int qos             = 0;
     private String broker       ;
     private String clientId     = "MqttClient";
     private MemoryPersistence persistence = new MemoryPersistence();
     private String TAG = "MQTTClient:";
     private Socket socket;
     private MqttClient client;
     private MqttMessage in;
     
     public MqttSubPub (Socket socket){
         this.socket = socket;

         String ip = socket.getInetAddress().getHostAddress();
         Log.i(TAG, "Broker IP is: " + ip);
         broker = "tcp://"+ip+":1883";
         try {
             client = new MqttClient(broker, clientId, persistence);
         } catch (MqttException e) {
             e.printStackTrace();
         }
         MqttConnectOptions connOpts = new MqttConnectOptions();
         connOpts.setCleanSession(true);
         client.setCallback(this);
         Log.i(TAG, "Connecting to broker: "+ broker);
         try {
             client.connect(connOpts);
         } catch (MqttException e) {
             e.printStackTrace();
         }
         Log.i(TAG, "Connected");

         in = new MqttMessage("Empty".getBytes());
     }
    public void doPublish(String topic, String mes) {
            MqttMessage message = new MqttMessage(mes.getBytes());
            message.setQos(qos);
        try {
            client.publish(topic, message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "Message published");
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "Disconnected");
    }

    public void doSubscribe(String topic) {
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable throwable) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {

        setChanged();
        notifyObservers(mqttMessage);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}

