package com.fca.uconnect.global;

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.GlobalUconnectDRM.DRM;
import com.fca.uconnect.global.GlobalUconnectExtProvision.ProvisioningPush;
import com.fca.uconnect.global.GlobalUconnectExtProvision.ProvisioningResponse;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForProvisioning {
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 int correlationId = 0;// The correlationId is a sender messageId so that Sender can recognize the message once its received response.

public SDPExampleForProvisioning() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtProvision.provisioningRequest);
	extRegistry.add(GlobalUconnectExtProvision.provisioningResponse);
	extRegistry.add(GlobalUconnectExtProvision.provisioningPush);
}

public UconnectMessage getProvisioningRespMsg(int correlationId) {
	messageId++;

	GlobalUconnectExtProvision.ProvisioningResponse.ResponseEnum resp = 
			GlobalUconnectExtProvision.ProvisioningResponse.ResponseEnum.SUCCESS;	
	ProvisioningResponse presp = ProvisioningResponse.newBuilder()
			.setResponseEnum(resp)
			.build();
	sessionId = ByteString.copyFrom(new byte[18]);
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.setCorrelationId(correlationId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtProvision.provisioningResponse, presp))
		.build();

	return msg;		
}

public void process() {

mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/PRVI/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);								
	GlobalUconnectExtProvision.ProvisioningRequest provisioningReqMsg = 
			msgIn.getMessages(0).getExtension(GlobalUconnectExtProvision.provisioningRequest);
	if (provisioningReqMsg.getVehicleId()!=null 
			&& provisioningReqMsg.getVehicleId().trim().length()>0) {
		correlationId=msgIn.getMessageId();
		sendMessage(getProvisioningRespMsg(correlationId));
		try {
			Thread.sleep(1000);//wait and send provisionpush
		} catch (InterruptedException e) {
		}
		sendMessage(getProvisionPushMsg( sessionId));
	}
	
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing Provisioning.");
	 
}
}
};

mqttClient.subscribe(iotTopic);

} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
	e.printStackTrace();
}

}
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 {						
	AWSIotMessage message = new 
			MessagePublisherListener(clientId+"/PRVI/",AWSIotQos.QOS1,msgOut);
	mqttClient.publish(message);

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