import jp.co.denso.fa.jcaosql.*;

public class Main {

	CaoSQLEngine eng = null;
	CaoSQLController ctrl = null;
	CaoSQLItem item = null;

	public void init() throws Exception {
		eng = CaoSQLEngine.createInstance();
		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]);

		ctrl.attachListener(
			new CaoSQLControllerListener() {
				public void onChangeItem(CaoSQLItem pIitem) {
					System.out.println("OnChangeItem: raised event");
					pIitem.release();
				}
				public void onChangeState(long state) {
					System.out.println("OnChangeState: raised event");
				}
			}
		);
		if (ctrl.getCount() < 1) {
			throw new Exception("there is no item settings.");
		}
		String[] item_names = ctrl.getItemNames();

	}

	public void dispose() {
		if (item != null) item.release();
		if (ctrl != null) {
			ctrl.detachListener();
			ctrl.release();
		}
		if (eng != null) eng.release();
	}

	public void addItem() throws Exception {
		System.out.println("add Item...");

		try {
			ctrl.start();
			Object[] objArray = new Object[27];
			objArray[0] = new String("AddItem1");
			objArray[1] = new Boolean(true);
			objArray[2] = new String("add_i1");
			objArray[3] = new Integer(0);
			ctrl.additem(objArray);
			sleep(1000);

			item = ctrl.Item("AddItem1");
			Integer value = new Integer(555);
			item.putValue(value);

			sleep(1000);

			ctrl.stop();
			item.release();
			System.out.println("add Item finished.");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removeItem() throws Exception {

		System.out.println("remove Item...");
		try {
			Object objIndex = new String("AddItem1");
			ctrl.removeitem(objIndex);
			System.out.println("remove Item finished.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {

		Main sample = new Main();

		try {
			sample.init();

			sample.addItem();
			// wait for event.
			sample.sleep(3000);
			sample.removeItem();
			sample.sleep(500);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sample.dispose();
		}
	}

	private synchronized void sleep(int time) {
		try {
			wait(time);
		} catch(InterruptedException e) {
		}
	}
}