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.GlobalUconnectExtFOTA.FirmwareUpdateNotification;
import com.fca.uconnect.global.GlobalUconnectExtFOTA.FirmwareUpdateNotification.FirmwareDescriptor;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForFOTA {
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.  
private List<UconnectAny> messages;

public SDPExampleForFOTA() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtFOTA.firmwareUpdateResponse);
}
//Disconnects MQTT 
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}

public UconnectMessage getFirmwareNotifyMsg(String taskId,List<FirmwareDescriptor> firmwareDescriptors) {
	messageId++;
	
	FirmwareUpdateNotification updateNotifyMsg = FirmwareUpdateNotification.newBuilder()
			.setFotaTaskId(taskId)
			.addAllFirmwareDescriptor(firmwareDescriptors)
			.build();

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

	return msg;		
}
public List<UconnectAny> getFOTADataMsg(){
	while(messages.isEmpty()){
		try {
			Thread.currentThread().sleep(3000);
		} catch (InterruptedException e) {
		}
	}
	return messages;
}
public void process() {
	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/FOTA/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);
	if(msgIn.getMessages(0).hasExtension(GlobalUconnectExtFOTA.firmwareUpdateResponse)){
		//Receive Firmware update response
    }
	
} catch( Exception ex) {
	ex.printStackTrace();
	System.out.println("Err processing message: "+ex+", try parsing FOTA.");
}
}
};
mqttClient.subscribe(iotTopic);
FirmwareDescriptor firmwareDescriptor = FirmwareDescriptor.newBuilder()
.setChecksum("CE114E4501D2F4E2DCEA3E17B546F339")
.setDescription("Update for ABC")
.setEcuAddress(956488)
.setExpireDate(456899)
.setPackageSize(10000)
.setFirmwareVersion("2.0")
.setUrl("https://abc.com")
.build();
List<FirmwareDescriptor> descriptors = new ArrayList<>();
descriptors.add(firmwareDescriptor);
sendMessage(getFirmwareNotifyMsg("AXCSEA1234",descriptors));
} 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+"/FOTA/", AWSIotQos.QOS1, msgOut);
} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
				e.printStackTrace();
			}		    	
	    }
	}).start();
}
public static void main(String[] args) {
	SDPExampleForFOTA m = new SDPExampleForFOTA();
	m.process();
}
}
