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.GlobalUconnectExtStolenVehAssist.StolenModeChangeRequest;
import com.fca.uconnect.global.GlobalUconnectExtStolenVehAssist.StolenModeChangeRequest.StolenModeCommand;
import com.fca.uconnect.global.GlobalUconnectExtStolenVehAssist.StolenVehicleControlRequest;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForStolenVehAssist {
private String clientId; // The clientId is unique to the device and obtained from the client X.509 certificate CN.
private ByteString sessionId; // The sessionId is assigned by the SDP to maintain a session independent of connection protocols.
private int messageId=10; // 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 int stolenVehicleControlmessageId;// This is to store message Id that sent with stolenVehicleControlRequest.
private boolean vehControlReqSent=false;//This is to check whether SDP received Vehicle Notification.
private List<UconnectAny> messages;

public SDPExampleForStolenVehAssist() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenModeChangeRequest);
	extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenModeChangeResponse);
	extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleInfoNotification);
	extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleControlResponse);
	extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleControlRequest);
}

public UconnectMessage getStolenVehicleControlReqMsg(boolean isIgnoreAccelerate,boolean isBlockIgnition){
	messageId++;
	stolenVehicleControlmessageId =messageId;
	StolenVehicleControlRequest sControlReqMsg = StolenVehicleControlRequest.newBuilder()
			.setIsIgnoreAccelerate(true)
			.setIsBlockIgnition(true)
			.build();
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtStolenVehAssist.stolenVehicleControlRequest,sControlReqMsg))
		.build();
	return msg;
	
}
public UconnectMessage getStolenModeChgReqMsg(boolean isActiveWhenKeyOff,int locationUpdateInterval,
		StolenModeCommand stolenModeCommand,int stolenModeDuration) {
	messageId++;
	StolenModeChangeRequest sreq = StolenModeChangeRequest.newBuilder()
			.setLocationUpdateInterval(locationUpdateInterval)
			.setStolenModeCommand(stolenModeCommand)
			.setStolenModeDuration(stolenModeDuration)
			.build();
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtStolenVehAssist.stolenModeChangeRequest,sreq))
		.build();

	return msg;		
}

public List<UconnectAny> process() {
	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");

try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/SVAS/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);			
	int msgId = msgIn.getMessageId();
		if(msgIn.getMessages(0).hasExtension(
		  GlobalUconnectExtStolenVehAssist.stolenVehicleInfoNotification)){
		//Receive Vehicle Information from TBM		
			
		if(!vehControlReqSent){
			vehControlReqSent=true;
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			sendMessage(getStolenVehicleControlReqMsg(true,true));//send Stolen Vehicle control Request	
		}
	}else if (msgIn.getMessages(0).hasExtension(
			GlobalUconnectExtStolenVehAssist.stolenModeChangeResponse) && 
			msgIn.getCorrelationId() ==messageId){
		if(messages==null)
			messages = new ArrayList<UconnectAny>();
		messages.add(msgIn.getMessages(0));
		//receive response from TBM
	}else if (msgIn.getMessages(0).hasExtension(
			GlobalUconnectExtStolenVehAssist.stolenVehicleControlResponse) && 
			msgIn.getCorrelationId()==stolenVehicleControlmessageId){
		//Receive Stolen VehicleControl Response
	}
		
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing Stolen Vehicle Assistance.");
	
}
}
};

sendMessage(getStolenModeChgReqMsg(false, 100000, StolenModeCommand.ENTER, 1000000));
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+"/SVAS/",AWSIotQos.QOS1,msgOut);
	mqttClient.publish(message);

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