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.DRM;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectAny;
import com.fca.uconnect.global.GlobalUconnectControl.UconnectMessage;
import com.fca.uconnect.global.GlobalUconnectExtActivation.ActivationResponse;
import com.fca.uconnect.global.GlobalUconnectExtProvision.ProvisioningPush;
import com.fca.uconnect.global.util.MessageUtil;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForActivation {
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 AWSIotTopic iotTopic; // The Topic object to subscribe for inbound messages.
private ExtensionRegistry extRegistry; // Google protocol buffers extension registry instance.
private boolean termsAndConditions;// flag to check whether User agreed or not for Terms and Condition.  
private int correlationId = 0;// The correlationId is a sender messageId so that Sender can recognize the message once its received response.

public SDPExampleForActivation() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtActivation.activationRequest);
	extRegistry.add(GlobalUconnectExtActivation.activationResponse);
	extRegistry.add(GlobalUconnectExtProvision.provisioningPush);
}
public static void main(String[] args) {
	SDPExampleForActivation m = new SDPExampleForActivation();
	m.process();
}
public UconnectMessage getActivationRespMsg(int correlationId,boolean isFromException) {
	messageId++;

	GlobalUconnectExtActivation.ActivationResponse.ResponseEnum resp = null;
	  
	  if(termsAndConditions){
		   resp = GlobalUconnectExtActivation.ActivationResponse.ResponseEnum.ACTIVATED;
	  }else if(!isFromException){
		  resp = GlobalUconnectExtActivation.ActivationResponse.ResponseEnum.FAILURE;
	  }else{
		  resp = GlobalUconnectExtActivation.ActivationResponse.ResponseEnum.RETRY_ABLE_FAILURE;
	  }
	ActivationResponse aresp = ActivationResponse.newBuilder()
			.setResponseEnum(resp)
			.build();
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.setCorrelationId(correlationId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtActivation.activationResponse, aresp))
		.build();

	return msg;		
}
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}
public void process() {

	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");

try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/UACT/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);			
	
	GlobalUconnectExtActivation.ActivationRequest activationReqMsg = msgIn.getMessages(0).getExtension(GlobalUconnectExtActivation.activationRequest);
	if (activationReqMsg.getVehicleId()!=null && activationReqMsg.getVehicleId().trim().length()>0  
	  &&activationReqMsg.getEmailAddress()!=null &&
		activationReqMsg.getEmailAddress().trim().length()>0 && validateEmail(activationReqMsg.getEmailAddress())) {
		correlationId=msgIn.getMessageId();
		if(activationReqMsg.getTcIndicator().equals(GlobalUconnectExtActivation.ActivationRequest.TCIndicatorEnum.AGREE))
			termsAndConditions=true;
		else
			termsAndConditions=false;
		sendMessage(getActivationRespMsg(correlationId,false));
	}
		try {
			Thread.sleep(1000);//simulating a delay between the login response message and pushing an updated provisioning message to the vehicle.  The delay represents additional processing time to lookup the services for the use.
		} catch (InterruptedException e) {
		}
		sendMessage(getProvisionPushMsg( sessionId));
	
	
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing Activation.");
	 sendMessage(getActivationRespMsg(correlationId,true));
}
}
};

mqttClient.subscribe(iotTopic);

} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
	e.printStackTrace();
}
}
public boolean validateEmail(String emailAddress){
	// this needs to be implemented with the appropriate logic to meet the requirements documented in the SFS.
	return true;
}
public UconnectMessage getProvisionPushMsg(ByteString sessionId) {
	messageId++;
	ByteString drmFile = ByteString.copyFrom(new byte[18]);
	DRM drm = DRM.newBuilder()
			.setDrmFile(drmFile)
			.build();
		 ProvisioningPush provisioningPush = ProvisioningPush.newBuilder()
				 .setDrm(drm)
				 .build();
UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		setExtension(GlobalUconnectExtProvision.provisioningPush, provisioningPush))					
		.build();
	return msg;		
}

public void sendMessage(UconnectMessage msg) {
final byte[] msgOut = msg.toByteArray();
new Thread(new Runnable() {

    @Override
public void run() {
try {	
	mqttClient.publish(clientId+"/UACT/", AWSIotQos.QOS1, msgOut);
} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
				e.printStackTrace();
			}		    	
	    }
	    
	}).start();
}

	
}
