
const SUBSCRIBE_TOPIC = 'dt/app_to_web/resp';
const PUBLISH_TOPIC   = 'dt/web_to_app/cmd';

var objMqttclient = '';

function initMqtt() {

    objMqttclient = new Paho.MQTT.Client( MOSQUITTO_BROKER_SERVER_IP, MOSQUITTO_BROKER_SERVER_WEBSOCKET_PORT, "diligence-raspberrypi-1" );

    console.log( objMqttclient );

    objMqttclient.onConnectionLost = onConnectionLost;
    objMqttclient.onMessageArrived = onMessageArrived;

    objMqttclient.connect( { 
        onSuccess: onConnect,
        onFailure: function( strFailureMessage ) {
            console.log( 'Failure in MQTT connection. Error - ' + strFailureMessage.errorMessage );

            $( '#js-mqtt-status' ).html( '<small class="badge badge-danger">Offline</small>' );
        }
    });
}

// OnConnect() function will be called from the respective UI files.

function onConnectionLost( responseObject ) {

    console.log( "Connection Lost" );
    console.log( responseObject );

    if( 0 !== responseObject.errorCode ) {
        
        console.log ("MQTT Connection Lost:" + responseObject.errorMessage);

        $( '#js-mqtt-status' ).html( '<small class="badge badge-danger">Offline</small>' );
    }
    
}

function onMessageArrived( objMessage ) {
    console.log( "Message Receviced " + objMessage.payloadString );

    processMessage( objMessage.payloadString );
}

function publishMessage( objSendMessage, strPublishTopic = PUBLISH_TOPIC ) {

    console.log( 'Publishing message' );
    
    objPahoMqttMessage = new Paho.MQTT.Message( objSendMessage );
    objPahoMqttMessage.destinationName = strPublishTopic;
    
    objMqttclient.send( objPahoMqttMessage );
}



