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.GlobalUconnectExtPC.PCUpdateConfigRequest;
import com.fca.uconnect.global.GlobalUconnectExtPC.PCUpdateConfigRequest.ConfigTypeVehicle;
import com.fca.uconnect.global.GlobalUconnectExtPC.PCUpdateConfigRequest.ConfigTypeVehicle.SpeedAlertConfig;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForPC {
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 SDPExampleForPC() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtPC.pcUpdateConfigResponse);
}
public UconnectMessage getPCConfigReqMsg() {
	messageId++;
	List<Integer> activeDays = new ArrayList<Integer>();
	activeDays.add(1);
	activeDays.add(2);
	SpeedAlertConfig speedAlertMsg =SpeedAlertConfig.newBuilder()
			.setBeginTime(1000)
			.setEndTime(10000)
			.setThresholdAbovePostedSpeed(60)
			.setThresholdAbsolute(70)
			.setThresholdPostedSpeedAbsent(80)
			.addAllActiveDaysOfWeek(activeDays)
			.build();
	ConfigTypeVehicle configTypeVehicle = ConfigTypeVehicle.newBuilder()
			.setUpdateSpeedAlertConfig(true)
			.addSpeedAlerts(speedAlertMsg)
			.build();
	PCUpdateConfigRequest pcUpdateConfigReq = PCUpdateConfigRequest.newBuilder()
			.setConfigTypeVehicle(configTypeVehicle)
			.build();
	
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setMessageId(messageId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtPC.pcUpdateConfigRequest,pcUpdateConfigReq ))
		.build();

	return msg;		
}
/**
 * This method demonstrates connecting to the AWS IoT mqtt broker and Subscribing  an Parental Control message to the PC topic.
 */
public  List<UconnectAny> process() {

	mqttClient = new AWSIotMqttClient("endpoint", clientId, "awsAccessKeyId", "awsSecretAccessKey");
try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/PC/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);			
	if(msgIn.getMessages(0).hasExtension(GlobalUconnectExtPC.pcUpdateConfigResponse)){
		GlobalUconnectExtPC.PCUpdateConfigResponse pcConfigResp = msgIn.getMessages(0).getExtension(GlobalUconnectExtPC.pcUpdateConfigResponse);
		if(messages==null)
			messages = new ArrayList<UconnectAny>();
		messages.add(msgIn.getMessages(0));
	}
} catch( Exception ex) {
	ex.printStackTrace();
}
}
};
sendMessage(getPCConfigReqMsg());
mqttClient.subscribe(iotTopic);

} catch (AWSIotException e) {
	System.out.println("Caught Exception "+e);
	e.printStackTrace();
}
return messages;
}
public void disconnect(){
	try {
		mqttClient.disconnect();
	} catch (AWSIotException e) {
		e.printStackTrace();
	}
}
public void sendMessage(UconnectMessage msg) {
final byte[] msgOut = msg.toByteArray();
new Thread(new Runnable() {

    @Override
public void run() {
try {						
	AWSIotMessage message = new 
			MessagePublisherListener(clientId+"/PC/",AWSIotQos.QOS1,msgOut);
	mqttClient.publish(message);

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