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

import com.etherios.connector.emulator.CloudConnector;
import javax.microedition.midlet.MIDlet;

/**
 * Cloud Connector for Java ME Tank demo application.
 *
 * <p>This sample simulates a tank with an input and an output valves.</p>
 * 
 * <p>The tank level and temperature is reported to Device Cloud every 
 * {@value TankMonitor#CLOUD_PUSH_TIMEOUT} seconds.</p>
 * 
 * <p>The level is calculated based on the status of the Valve-In and Valve-Out 
 * that can be remotely managed.</p>
 * 
 * <p>The temperature is randomly generated with a minimum value of 20C
 * and a maximum value of 30C.</p>
 *
 * <p>For a complete description on the example, refer to the 'ReadMe.txt' file
 * included in the root directory.</p>
 */
public class MainApp extends MIDlet {

	/* Variables */

	private static CloudConnector connector;

	private static ConnectorEventsListener connectorEventsListener;

	private static SimulatedTank tank;

	private static TankMonitor tankMonitor;

	@Override
	public void startApp() {
		// Create the Cloud Connector object.
		if (connector == null)
			connector = new CloudConnector();
		
		// Create the simulated tank.
		if (tank == null)
			tank = new SimulatedTank(connector.getLogger());
		
		// Register the listener to handle incoming device requests to remotely
		// open/close the tank valves.
		if (tankMonitor == null) {
			tankMonitor = new TankMonitor(connector, tank);
			connector.registerDeviceRequestListener(tankMonitor);
		}
		
		// Register the event listener.
		if (connectorEventsListener == null) {
			connectorEventsListener = new ConnectorEventsListener(tankMonitor);
			connector.registerEventsListener(connectorEventsListener);
		}
		
		// Start connection to Device Cloud.
		connector.start();
		// Start tank simulation.
		tank.startSimulation();
		// Start tank monitoring.
		tankMonitor.start();
	}

	@Override
	public void pauseApp() {
		tankMonitor.stop();
		tank.stopSimulation();
		connector.stop();
	}

	@Override
	public void destroyApp(boolean unconditional) {
		tankMonitor.stop();
		tank.stopSimulation();
		connector.stop();
		notifyDestroyed();
	}
}
