/**
 * Copyright (c) 2014 Etherios, a Division of Digi International, Inc.
 * All rights not expressly granted are reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Etherios 11001 Bren Road East, Minnetonka, MN 55343
 * =======================================================================
 */
package com.etherios.connector.devicerequest;

import com.etherios.connector.core.facilities.messaging.IDeviceRequestListener;
import com.etherios.connector.core.log.Logger;
import com.etherios.connector.emulator.CloudConnector;
import java.io.InputStream;
import java.util.Calendar;

/**
 * Class to manage the received device requests.
 *
 * <p>It listens and handles incoming device requests by implementing the
 * {@link DataRequestHandler} interface.</p>
 */
public class DeviceRequestListener implements IDeviceRequestListener {

	/* Constants */

	// This defines the target name we will use to receive data requests.
	private static final String TARGET_SCREENSHOT = "screenshot";

	// Device request error messages
	private static final String INVALID_REQUEST_DATA = "Invalid request data";

	/* Variables */

	private final CloudConnector connector;

	/**
	 * Class constructor. Instances a new <code>DeviceRequestHandler</code> to
	 * manage the incoming device requests.
	 *
	 * @param connector
	 */
	public DeviceRequestListener(CloudConnector connector) {
		this.connector = connector;
	}

	@Override
	public String handleDeviceRequest(String target, byte[] data) {
		return handleDeviceRequest(target, new String(data));
	}

	@Override
	public String handleDeviceRequest(String target, String data) {
		if (target == null || !target.equals(TARGET_SCREENSHOT)) {
			return null; // Target not registered.
		}
		if (data == null) {
			return INVALID_REQUEST_DATA; // Data cannot be null.
		}
		data = data.trim();
		if (data.length() == 0) {
			return INVALID_REQUEST_DATA;
		}

		// Not really a screenshot, an image in the project.
		InputStream imageStream = Class.class.getClass().getResourceAsStream("/image.png");
		if (imageStream == null) {
			String error = "Error capturing screenshot.";
			Logger.logSystemError(connector.getLogger(), ConnectorEventsListener.LOGGER_PREFIX + error);
			return error;
		}

		// Get the local file of the screen shot.
		String filename = Calendar.getInstance().getTime().toString().replace(':', '.');
		filename = filename.replace(' ', '_').replace('+', '_') + ".png";

		// Get destination path in Device Cloud.
		String destPath = data + "/" + filename;

		// Upload the screen shot file to Device Cloud.
		connector.sendDataToRemoteFile(imageStream, destPath, "image/png");

		String successMessage = "Screenshot uploaded to "
				+ connector.getDeviceID() + "/" + destPath;
		Logger.logSystemInfo(connector.getLogger(), ConnectorEventsListener.LOGGER_PREFIX + successMessage);
		return successMessage;
	}
}
