/**********************************************************************************************
 * 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.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.GlobalUconnectExtActivation.ActivationRequest;
import com.fca.uconnect.global.GlobalUconnectExtActivation.ActivationResponse;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

/**
 * This example class demonstrates how to use the AWS IoT mqtt client to send a Uconnect Activation message 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 TBMExampleForActivation {

	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 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 TBMExampleForActivation() {
		extRegistry = ExtensionRegistry.newInstance();
		extRegistry.add(GlobalUconnectExtActivation.activationResponse);
		extRegistry.add(GlobalUconnectExtProvision.provisioningPush);
		this.semaphore = new Semaphore();
	}
	
	/**
	 * This method generates a Protocol Buffer Uconnect Message given the required inputs for Activation.
	 * 
	 * @param vehicleId
	 * @param firstName
	 * @param lastName
	 * @param emailAddress
	 * @param acceptTandC
	 * @return UconnectMessage Protocol Buffer
	 */
	public UconnectMessage getActivationReqMsg(String vehicleId,String firstName,String lastName,
		String emailAddress, boolean acceptTandC) {
		this.messageId++;
		sessionId = ByteString.copyFrom(new byte[18]);
		GlobalUconnectExtActivation.ActivationRequest.TCIndicatorEnum indicatorEnum;
		
		if (acceptTandC) {
			indicatorEnum = GlobalUconnectExtActivation.ActivationRequest.TCIndicatorEnum.AGREE;
		}
		else {
			indicatorEnum = GlobalUconnectExtActivation.ActivationRequest.TCIndicatorEnum.DISAGREE;			
		}
	
		ActivationRequest activationReq = ActivationRequest.newBuilder()
			.setVehicleId(vehicleId)
			.setEmailAddress(emailAddress)
			.setFirstName(firstName)
			.setLastName(lastName)
			.setTcIndicator(indicatorEnum)
			.build();
    		
		UconnectMessage msg = UconnectMessage.newBuilder()
			.setTimestamp(System.currentTimeMillis())
			.setMessageId(messageId)
			.addMessages(UconnectAny.newBuilder().
			 setExtension(GlobalUconnectExtActivation.activationRequest, activationReq))
			.build();

		return msg;		
	}
	
	/**
	 * This method demonstrates connecting to the AWS IoT mqtt broker and publishing an Activation message to the UACT topic.
	 */
	public List<UconnectAny> process() {
		
		mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
		try {			
			mqttClient.connect();						
						
			iotTopic = new AWSIotTopic(clientId+"/UACT/", AWSIotQos.QOS1) {
				//this code will be executed upon receiving an ActivationRespose message.
				public void onMessage(AWSIotMessage msg) {
					try{
					UconnectMessage msgIn;
						msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);
					if (msgIn.getCorrelationId()==messageId && msgIn.getMessages(0).hasExtension(GlobalUconnectExtActivation.activationResponse)) {
						if(messages==null)
							messages = new ArrayList<UconnectAny>();
						messages.add(msgIn.getMessages(0));
						ActivationResponse activationMsg = msgIn.getMessages(0).getExtension(GlobalUconnectExtActivation.activationResponse);
						semaphore.unlock();// Releasing the lock as it received response
					}else if(messages!=null && messages.size()>0){
						receivedResponse=true;
						messages.add(msgIn.getMessages(0));
					}
				
			} catch( Exception ex) {
				ex.printStackTrace();
				System.out.println("Err processing message: "+ex+", try parsing Activation.");
			}
			}
			};
			mqttClient.subscribe(iotTopic);
			UconnectMessage msg = getActivationReqMsg("562X4423AE122","fname","lname","flname@google.com",true);
			AWSIotMessage message = new MessagePublisherListener("/UACT/"+clientId,AWSIotQos.QOS1,msg.toByteArray());
			mqttClient.publish(message);
			//This is just to simulate a delay between sending Activation request and receiving Activation response and its just a place holder ,The onMessage method Handles callback
			this.semaphore.lock();		
			
			if(messages!=null)
				return messages;
		} catch (AWSIotException ex) {
			System.out.println("Caught AWS Exception "+ex);
			ex.printStackTrace();
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * Example main to launch example.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		TBMExampleForActivation example = new TBMExampleForActivation();
		example.process();
	}

}
