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.GlobalUconnectExtWIFIHotSpot.DataPackageStatusResponse;
import com.fca.uconnect.global.GlobalUconnectExtWIFIHotSpot.WifiPackageDataStatus;
import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;

public class SDPExampleForWifiHotSpot {
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.
private boolean messageReceived = false; // flag to wait for the message as part of this example. 

public SDPExampleForWifiHotSpot() {
	extRegistry = ExtensionRegistry.newInstance();
	extRegistry.add(GlobalUconnectExtWIFIHotSpot.dataPackageStatusRequest);
	extRegistry.add(GlobalUconnectExtWIFIHotSpot.dataPackageStatusResponse);
	extRegistry.add(GlobalUconnectExtWIFIHotSpot.wifiPackageDataStatus);
}

public UconnectMessage getWifiRespMsg(int correlationId,boolean isFromException) {
	messageId++;

	GlobalUconnectExtWIFIHotSpot.DataPackageStatusResponse.ResponseEnum resp = null;
	  if(isFromException)
		   resp = GlobalUconnectExtWIFIHotSpot.DataPackageStatusResponse.ResponseEnum.FAILURE;
	  else
		   resp = GlobalUconnectExtWIFIHotSpot.DataPackageStatusResponse.ResponseEnum.SUCCESS;
		   WifiPackageDataStatus wifiPackageDataStatus = WifiPackageDataStatus.newBuilder()
				   .setIsLowAlertFlag(false)
				   .setTotalVolume(1000000) //this is in KB
				   .setUsedVolume(500000)
				   .setUsedTiming(20)   //days
				   .setTotalTiming(30)
				   .build();
	DataPackageStatusResponse dataPackageStatusResponse = DataPackageStatusResponse.newBuilder()
			.setResponseEnum(resp)
			.setPackageStatus(wifiPackageDataStatus)
			.build();
	
	UconnectMessage msg = UconnectMessage.newBuilder()
		.setTimestamp(System.currentTimeMillis())
		.setSessionId(sessionId)
		
		.setMessageId(messageId)
		.setCorrelationId(correlationId)
		.addMessages(UconnectAny.newBuilder().
		 setExtension(GlobalUconnectExtWIFIHotSpot.dataPackageStatusResponse, dataPackageStatusResponse))
		.build();

	return msg;		
}

public void process() {

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

try {			
mqttClient.connect();						
 iotTopic = new AWSIotTopic("/WIFI/#",AWSIotQos.QOS1){
	public void onMessage(AWSIotMessage msg) {
try {
	
	UconnectMessage	msgIn = UconnectMessage.parseFrom(msg.getPayload(),extRegistry);								
	GlobalUconnectExtWIFIHotSpot.DataPackageStatusRequest wifiReqMsg = msgIn.getMessages(0).getExtension(GlobalUconnectExtWIFIHotSpot.dataPackageStatusRequest);
		correlationId=msgIn.getMessageId();
		sendMessage(getWifiRespMsg(correlationId,false));
  	
		try {
			Thread.sleep(1000);//wait and send WifiDataPush
		} catch (InterruptedException e) {
		}
		sendMessage(getWifiLowAlertPushMsg(sessionId));
	
	
} catch( Exception ex) {
	System.out.println("Err processing message: "+ex+", try parsing Activation.");
	 sendMessage(getWifiRespMsg(correlationId,true));
}
}
};

mqttClient.subscribe(iotTopic);

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


}
public UconnectMessage getWifiLowAlertPushMsg(ByteString sessionId) {
	messageId++;
	
	WifiPackageDataStatus packagStatus = WifiPackageDataStatus.newBuilder()
			   .setIsLowAlertFlag(true)
			   .setTotalVolume(1000000) //this is in KB
			   .setUsedVolume(900000)
			   .setUsedTiming(20)
			   .setTotalTiming(30)
			   .build();
	  
		
		UconnectMessage msg = UconnectMessage.newBuilder()
				.setTimestamp(System.currentTimeMillis())
				.setMessageId(messageId)
				.addMessages(UconnectAny.newBuilder().setExtension(GlobalUconnectExtWIFIHotSpot.wifiPackageDataStatus, packagStatus))
				.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+"/WIFI/",AWSIotQos.QOS1,msgOut);
	mqttClient.publish(message);

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