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.GlobalUconnectExtAOTA.ApplicationUpdateNotification;
import com.fca.uconnect.global.GlobalUconnectExtAOTA.InitiateDiscrepancyCheck;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForAOTA {
private String clientId; // The clientId is unique to the device and obtained from the client X.509 certificate CN.
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.  

public SDPExampleForAOTA() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtAOTA.discrepancyCheck);
	extRegistry.add(GlobalUconnectExtAOTA.updateStatusNotification);
}
//Disconnects MQTT 
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}
public UconnectMessage getInitiateDescMsg(){
	messageId++;
	InitiateDiscrepancyCheck descCheckmsg = InitiateDiscrepancyCheck.newBuilder()
			.build();
	UconnectMessage msg = UconnectMessage.newBuilder()
			.setTimestamp(System.currentTimeMillis())
			.setMessageId(messageId)
			.addMessages(UconnectAny.newBuilder().
			 setExtension(GlobalUconnectExtAOTA.initiateDiscrepancyCheck, descCheckmsg))
			.build();

		return msg;		
}
public UconnectMessage getAppUpdateNotifyMsg(String appId,String description,long expireTime,
			int size,String version,String checkSum,String url) {
	messageId++;
	
	ApplicationUpdateNotification updateNotifyMsg = ApplicationUpdateNotification.newBuilder()
			.setAppId(appId)
			.setDescription(description)
			.setExpireDate(expireTime)
			.setPackageSize(size)
			.setChecksum(checkSum)
			.setVersion(version)
			.setUrl(url)
			.build();

	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtAOTA.applicationUpdateNotification, updateNotifyMsg))
		.build();

	return msg;		
}

public void process() {
	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/AOTA/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);
	if(msgIn.getMessages(0).hasExtension(GlobalUconnectExtAOTA.discrepancyCheck)){
		//Receive Discrepancy Check Message
		//send app update
		long expireTime = System.currentTimeMillis()+1000000;
		sendMessage(getAppUpdateNotifyMsg("APPID","DESCRPTION",expireTime,32,"VERSION","CHECKSUM","URL"));
    }
	
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing AOTA.");
}
}
};
mqttClient.subscribe(iotTopic);
sendMessage(getInitiateDescMsg());

} catch (AWSIotException e) {
	System.out.println("Caught 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(clientId+"/AOTA/", AWSIotQos.QOS1, msgOut);
} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
				e.printStackTrace();
			}		    	
	    }
	}).start();
}
public static void main(String[] args) {
	SDPExampleForAOTA m = new SDPExampleForAOTA();
	m.process();
}
}
