/**********************************************************************************************
 * This example code is provided for illustrative purposes only and provided 'AS IS' without 
 * warranty of any kind.
 * 
 * Copyright ©2014 Chrysler Group LLC.  All Rights Reserved.  All information contained herein is,
 * and remains the property of Chrysler Group LLC and its suppliers, if any.  The intellectual and
 * technical concepts contained herein are proprietary to Chrysler Group LLC and its suppliers
 * and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade
 * secret or copyright law. Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from Chrysler Group LLC.
 *
 * Chrysler, Jeep, Dodge, Ram, SRT, Mopar and the Pentastar logo are registered trademarks of
 * Chrysler Group LLC. FIAT is a registered trademark of Fiat group Marketing & Corporate
 * Communication S.p.A. used under license by Chrysler Group LLC.
 *********************************************************************************************/
package com.fca.uconnect.global;

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.Location;
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.StolenModeChangeResponse;
import com.fca.uconnect.global.GlobalUconnectExtStolenVehAssist.StolenVehicleControlResponse;
import com.fca.uconnect.global.GlobalUconnectExtStolenVehAssist.StolenVehicleControlResponse.StolenVehControlResponseEnum;
import com.fca.uconnect.global.GlobalUconnectExtStolenVehAssist.StolenVehicleInfoNotification;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

/**
 * This example class demonstrates how to use the AWS IoT mqtt client to send/receive a Uconnect StolenVehicleAssistance messages to the SDP and wait for a response message.   
 * This code is only for reference and is furnished without warranty.....
 * 
 * @author FCA Global V2C API Team
 *
 */
public class TBMExampleForStolenVehAssist {

	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; // 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 boolean receivedResponse = false; // flag to wait for the response as part of this example.
	private AWSIotTopic iotTopic; // The Topic object to subscribe for inbound messages.
	private ExtensionRegistry extRegistry; // Google protocol buffers extension registry instance.
	private int correlationId = 0;// The correlationId is a sender messageId so that Sender can recognize the message once its received response.
	private Semaphore semaphore;//The semaphore object is used to wait for a response.
	List<UconnectAny> messages ;

	/**
	 * Constructor - initialize protocol buffer extension registry for parsing incoming Uconnect Messages.
	 */
	public TBMExampleForStolenVehAssist() {
		extRegistry = ExtensionRegistry.newInstance();
		extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenModeChangeRequest);
		extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenModeChangeResponse);
		extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleInfoNotification);
		extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleControlRequest);
		extRegistry.add(GlobalUconnectExtStolenVehAssist.stolenVehicleControlResponse);
		this.semaphore = new Semaphore();
	}
	
	/**
	 * This method generates a Protocol Buffer Uconnect Message given the required inputs for StolenModeChangeResponse.
	 * 
	 * @param isStolenModeActive
	 * @return UconnectMessage Protocol Buffer
	 */
	public UconnectMessage getStolenModeChangeRespMsg(boolean isStolenModeActive) {
		this.messageId++;
		sessionId = ByteString.copyFrom(new byte[18]);
		StolenModeChangeResponse stolenModeChgResp = StolenModeChangeResponse.newBuilder()
			.setIsStolenModeActive(isStolenModeActive)
			.build();
    		
		UconnectMessage msg = UconnectMessage.newBuilder()
			.setTimestamp(System.currentTimeMillis())
			.setMessageId(messageId)
			.setCorrelationId(correlationId)
			.addMessages(UconnectAny.newBuilder().
			setExtension(GlobalUconnectExtStolenVehAssist.stolenModeChangeResponse, stolenModeChgResp))
			.build();
		return msg;		
	}
	public UconnectMessage getStolenVehNotificationMsg(Location vehicleLocation,boolean isBlockIgnitionActive,
					boolean isIgnoreAccelerateActive){
		messageId++;
		StolenVehicleInfoNotification notifyMsg =StolenVehicleInfoNotification.newBuilder()
				.setIsBlockIgnitionActive(isBlockIgnitionActive)
				.setIsIgnoreAccelerateActive(isIgnoreAccelerateActive)
				.setVehicleLocation(vehicleLocation)
				.build();
		UconnectMessage msg = UconnectMessage.newBuilder()
				.setTimestamp(System.currentTimeMillis())
				.setMessageId(messageId)
				.addMessages(UconnectAny.newBuilder().
				setExtension(GlobalUconnectExtStolenVehAssist.stolenVehicleInfoNotification, notifyMsg))
				.build();
			return msg;		
	}
public UconnectMessage getStolenVehicleControlRespMsg(StolenVehControlResponseEnum respEnum){
messageId++;
StolenVehicleControlResponse respMsg =StolenVehicleControlResponse.newBuilder()
		.setStolenVehControlResponseEnum(respEnum)
		.build();
UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.setCorrelationId(correlationId)
		.addMessages(UconnectAny.newBuilder().
		setExtension(GlobalUconnectExtStolenVehAssist.stolenVehicleControlResponse, respMsg))
		.build();
	return msg;		
}
	/**
	 * This method demonstrates connecting to the AWS IoT mqtt broker and publishing an StolenVehAsist messages to the SVAS topic.
	 */
	public void process() {
		mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
		try {			
			mqttClient.connect();						
			iotTopic = new AWSIotTopic(clientId+"/SVAS/", AWSIotQos.QOS1) {
	public void onMessage(AWSIotMessage msg) {
		try{
		UconnectMessage msgIn;
			msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);
			correlationId=msgIn.getMessageId();
	if (msgIn.getMessages(0).hasExtension(GlobalUconnectExtStolenVehAssist.stolenModeChangeRequest)) {
		semaphore.unlock();// Releasing the lock 
		StolenModeChangeRequest stolenModelChgReqMsg = msgIn.getMessages(0).getExtension(
				GlobalUconnectExtStolenVehAssist.stolenModeChangeRequest);
		boolean isStolenModeActive=false;
	if(stolenModelChgReqMsg.getStolenModeCommand().equals(StolenModeCommand.ENTER))
			isStolenModeActive=true;
		UconnectMessage respMsg = getStolenModeChangeRespMsg(isStolenModeActive);
		sendMessage(respMsg);
		//For Every interval send Vehicle Notification to SDP with location and Mode
		int i=1;
		while(isStolenModeActive){
			Location vehicleLocation = Location.newBuilder()
					.setPositionLatitude(42.480201F+(i*0.0001F))
					.setPositionLongitude(-83.671875F+(i*0.0001F))
					.build();
			boolean isBlockIgnitionActive=false;
			boolean isIgnoreAccelerateActive=false;
			Thread.sleep(stolenModelChgReqMsg.getLocationUpdateInterval());
			sendMessage(getStolenVehNotificationMsg(vehicleLocation, 
					isBlockIgnitionActive, isIgnoreAccelerateActive));
			i++;
		}
	}else if(msgIn.getMessages(0).hasExtension(
			GlobalUconnectExtStolenVehAssist.stolenVehicleControlRequest)){
		correlationId=msgIn.getMessageId();
		sendMessage(getStolenVehicleControlRespMsg(StolenVehControlResponseEnum.SUCCESS));
	}
	} catch( Exception ex) {
		ex.printStackTrace();
		System.out.println("Err processing message: "+ex+", try parsing StolenVehAssistance messages.");
	}
 }
};
			mqttClient.subscribe(iotTopic);
			this.semaphore.lock();	// lock thread

		} catch (AWSIotException ex) {
			System.out.println("Caught AWS Exception "+ex);
			ex.printStackTrace();
		}  catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMessage(UconnectMessage msg) {
		final byte[] msgOut = msg.toByteArray();
		new Thread(new Runnable() {
		    @Override
		public void run() {
		try {						
			mqttClient.publish("/SVAS/"+clientId, AWSIotQos.QOS1, msgOut);
		} catch (AWSIotException e) {
			System.out.println("Caught Exception "+e);
						e.printStackTrace();
					}		    	
			    }
			}).start();
		}
	
	/**
	 * Example main to launch example.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		TBMExampleForStolenVehAssist example = new TBMExampleForStolenVehAssist();
		example.process();
	}
}