import jp.co.denso.fa.jcaosql.*;

public class Main {

	public static void main(String[] args) {

		CaoSQLEngine eng = null;
		CaoSQLController ctrl = null;
		CaoSQLItem item = null;

		try {
			eng = CaoSQLEngine.createInstance();
			System.out.println("careated Engine...");
			Main mn = new Main();
			mn.sleep(1000);

			if (eng.count() < 1) {
				throw new Exception("there is no controller settings.");
			}
			String[] ctrl_names = eng.getControllerNames();
			ctrl = eng.Controller(ctrl_names[0]);
			System.out.println("Getting Controller ["+ ctrl_names[0] + "]");

			if (ctrl.getCount() < 1) {
				throw new Exception("there is no item settings.");
			}
			String[] item_names = ctrl.getItemNames();
			item = ctrl.Item(item_names[0]);
			System.out.println("Getting Item ["+ item_names[0] + "]");

			// --- set value
			Object[] varval = new Object[3];
			varval[0] = new Integer(100);
			varval[1] = null;
			varval[2] = new String("foo");

			item.putValue(varval);

			// wait for value sync
			mn.sleep(1000);

			// --- get vaule
			System.out.println("----- item info -----");
			System.out.println("VariableName: " + item.getSettingData(new Integer(0)));
			Object value = item.getValue();
			String vartype;
			if (value.getClass().isArray()) {
				System.out.println("VarType: VT_ARRAY |");
				Object[] array = (Object[]) value;
				for (int i = 0; i < array.length; i++) {
					System.out.println("\t" + i + ": VarType: " + getStringByValue(array[i]));
					System.out.println("\t" + i + ": Value: " + array[i]);
				}
			} else {
				System.out.println("VarType: " + getStringByValue(value));
				System.out.println("Value: " + value.toString());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (item != null) item.release();
			if (ctrl != null) ctrl.release();
			if (eng != null) eng.release();
		}
	}

	private synchronized void sleep(int time) {
		try {
			wait(time);
		} catch(InterruptedException e) {
		}
	}

	private static String getStringByValue(Object value) {

		if (value == null) {
			return "VT_EMPTY";
		} else if (value instanceof Integer) {
			return "VT_I4";
		} else if (value instanceof Short) {
			return "VT_I2";
		} else if (value instanceof String) {
			return "VT_BSTR";
		} else if (value instanceof Byte) {
			return "VT_UI1";
		} else if (value instanceof Character) {
			return "VT_I1";
		} else if (value instanceof java.util.Date) {
			return "VT_DATE";
		} else if (value instanceof Boolean) {
			return "VT_BOOL";
		} else if (value instanceof Float) {
			return "VT_R4";
		} else if (value instanceof Double) {
			return "VT_R8";
		}

		return "VarType Error";

	}

}