/**
 * 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.datapush;

import com.etherios.connector.core.log.Logger;
import com.etherios.connector.emulator.CloudConnector;
import java.io.IOException;
import java.io.InputStream;

/**
 * Class to manage the Data Push upload.
 *
 * <p>It simulates a security camera that uploads a video to Device Cloud 
 * every {@value #REFRESH_TIMEOUT} milliseconds.</p>
 */
public class CameraMonitor {

	/* Constants */
	
	// Timeout between uploads.
	private static final int TIMEOUT = 10 * 1000; // 10 seconds
	
	// Path of the remote files.
	private static final String DEST_PATH = "camera/";
	
	// Videos to upload.
	private static final String[] VIDEOS = {"1.mp4", "2.mp4", "3.mp4", "4.mp4", "5.mp4"};

	/* Variables */

	// Cloud Connector.
	private CloudConnector connector;

	/**
	 * Class constructor. Instances a new {@code CameraMonitor} object to 
	 * manage the Data Push upload.
	 * 
	 * @param connector Cloud Connector instance.
	 */
	public CameraMonitor(CloudConnector connector) {
		this.connector = connector;
	}
	
	/**
	 * Starts the monitoring.
	 * 
	 * <p>Uploads every {@value #REFRESH_TIMEOUT} ms. a video from the 
	 * 'videos' directory until all the clips have been uploaded.</p>
	 */
	public void start() {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// Upload all the files inside the 'videos' folder.
				for (String clip : VIDEOS) {
					InputStream is = null;
					try {
						Thread.sleep(TIMEOUT);
						if (connector.isConnected()) {
							is = Class.class.getClass().getResourceAsStream("/videos/" + clip);
							if (is == null)
								Logger.logSystemError(connector.getLogger(), "Could not find the file /videos/" + clip);
							else
								connector.sendDataToRemoteFile(is, DEST_PATH + clip, "video/mp4");
						} else
							Logger.logSystemError(connector.getLogger(), ConnectorEventsListener.LOGGER_PREFIX 
									+ "Could not send the video '" + clip + "'. Cloud Connector is not connected.");
					} catch (InterruptedException ex) {
						Logger.logException(connector.getLogger(), ex);
					} finally {
						if (is != null) {
							try {
								is.close();
							} catch (IOException ex) {}
						}
					}
				}
			}
		});
		thread.start();
	}
}