package com.fca.uconnect.global;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMessage;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import com.amazonaws.services.iot.client.AWSIotQos;
import com.amazonaws.services.iot.client.AWSIotTopic;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectAny;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectMessage;
import com.fca.uconnect.global.GlobalUconnectExtVehicleMessaging.VehicleMessagePublish;
import com.fca.uconnect.global.GlobalUconnectExtVehicleMessaging.VehicleMessagePublish.LanguageString;
import com.fca.uconnect.global.GlobalUconnectExtVehicleMessaging.VehicleMessagePublish.MessageType;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForVehMessaging {
private String clientId; // The clientId is unique to the device and obtained from the client X.509 certificate CN.
private int messageId; // The messageId is a sequential number incremented and assigned to each message sent from the client.
private AWSIotMqttClient mqttClient; // The mqtt client object from the AWS IoT client library. 
private AWSIotTopic iotTopic; // The Topic object to subscribe for inbound messages.
private ExtensionRegistry extRegistry; // Google protocol buffers extension registry instance.
private List<UconnectAny> messages;//This is for Junit Tests.


public SDPExampleForVehMessaging() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtVehicleMessaging.vehicleMessageAck);
	extRegistry.add(GlobalUconnectExtVehicleMessaging.vehicleMessageDispositionPublish);
}
public UconnectMessage getVehicleMessagingPubMsg(String vin,MessageType messageType,LanguageString lang) {
	messageId++;
	VehicleMessagePublish pubMsg = VehicleMessagePublish.newBuilder()
			.setVin(vin)
			.setMessageType(messageType)
			.addMessage(lang)
			.build();
	
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtVehicleMessaging.vehicleMessagePublish,pubMsg))
		.build();

	return msg;		
}

/**
 * This method demonstrates connecting to the AWS IoT mqtt broker and Subscribing  an Parental Control message to the VehicleMessaging topic.
 */
public List<UconnectAny> process() {

	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/IVM/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);			
	if(msgIn.getMessages(0).hasExtension(GlobalUconnectExtVehicleMessaging.vehicleMessageAck)){
		GlobalUconnectExtVehicleMessaging.VehicleMessageAck acknowledgement= msgIn.getMessages(0).getExtension(GlobalUconnectExtVehicleMessaging.vehicleMessageAck);
		if(messages==null)
			messages = new ArrayList<UconnectAny>();
		messages.add(msgIn.getMessages(0));
	}
} catch( Exception ex) {
	ex.printStackTrace();
}
}
};
LanguageString lang = LanguageString.newBuilder()
.setLanguage("ENGLISH")
.setMessageText("Your Vehicle is Due for Service")
.build();

sendMessage(getVehicleMessagingPubMsg("1HGCM82633A004352",MessageType.SERVICE_NOTICE,lang));
mqttClient.subscribe(iotTopic);


} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
	e.printStackTrace();
}
return messages;
}
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}

public void sendMessage(UconnectMessage msg) {
final byte[] msgOut = msg.toByteArray();
new Thread(new Runnable() {
    @Override
public void run() {
try {						
	AWSIotMessage message = new 
			MessagePublisherListener(clientId+"/IVM/",AWSIotQos.QOS1,msgOut);
	mqttClient.publish(message);

} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
				e.printStackTrace();
			}		    	
	    }
	}).start();
}
public static void main(String[] args) {
	SDPExampleForVehMessaging m = new SDPExampleForVehMessaging();
	m.process();
}
}
