/* 
 * 
 * Copyright © 2009   Rose + Herleth GbR   www.ezcontrol.de
 * 
 * 
 * xs1console - control program for EZcontrol XS1
 * 
 * 03.08.2009 1.00  - Initial Release
 * 
 */


package de.ezcontrol.xs1console;

public class XS1Console {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		boolean valid = true;
		int n = 0;
		String type = null;
		boolean unit = false;
		boolean timestamp = false;
		boolean set = false;
		double value = 0;
		int i = 1;
		if (args.length >= 5) {
			if (args[0].length() < 2) {
				System.out.println(args[0]
						+ " is not a valid hostname or ip address.");
				valid = false;
			}
			while (i < args.length) {
				if (args[i].equalsIgnoreCase("-type")) {
					i++;
					if (args[i].charAt(0) == 'a') {
						type = "actuator";
					} else if (args[i].charAt(0) == 's') {
						type = "sensor";
					} else {
						System.out.println(args[i]
								+ ": argument type must a or s.");
						valid = false;
					}
				} else if (args[i].equalsIgnoreCase("-n")) {
					i++;
					try {
						n = Integer.valueOf(args[i]);
					} catch (NumberFormatException e) {
						System.out.println(args[i]
								+ ": argument must be a number.");
						valid = false;
					}
					if ((n < 1) || (n > 128)) {
						System.out.println(args[i]
								+ ": argument not a valid number.");
						valid = false;
					}

				} else if (args[i].equalsIgnoreCase("-value")) {
					set = true;
					i++;
					try {
						value = Double.valueOf(args[i]);
					} catch (NumberFormatException e) {
						System.out.println(args[i]
								+ ": argument must be a number.");
						valid = false;
					}
				} else if (args[i].equalsIgnoreCase("-u")) {
					unit = true;
				} else if (args[i].equalsIgnoreCase("-t")) {
					timestamp = true;
				}
				i++;
			}
		}
		if ((valid) && (n != 0) && (type != null)) {
			XS1JSON json = new XS1JSON(args[0]);
			if (set) {
				if (json.setValue(type, n, value)) {
					System.out.println("OK");
					System.exit(0);
				} else {
					System.out.println("ERROR");
					System.exit(1);
				}
			} else {
				String response = json.getValue(type, n, timestamp, unit);
				System.out.println(response);
				System.exit(0);
			}
		} else {
			System.out.println("usage:");
			System.out
					.println("xs1console <IP|hostname> <-type a|s> <-n number> [-u,-t]|[-value value]");
			System.out.println("-type	a=actuator, s=sensor");
			System.out.println("-n		number=number of storage on XS1");
			System.out.println("-value	value to set, return is true if successful");
			System.out.println("or");
			System.out.println("-u		output with unit");
			System.out.println("-t		output with timestamp");
			System.exit(1);
		}
	}
}

