package astri.test.testMasterCompImpl;

import java.util.logging.Logger;

import alma.ACS.MasterComponent;
import alma.ACS.MasterComponentHelper;
import alma.ACS.ROstringSeq;
import alma.ACS.MasterComponentImpl.StateChangeListener;
import alma.ACS.MasterComponentImpl.StateChangeSemaphore;
import alma.ACS.MasterComponentPackage.SubsystemStateEvent;
import alma.JavaContainerError.wrappers.AcsJContainerServicesEx;
import alma.acs.component.client.ComponentClient;
import alma.acs.util.AcsLocations;

public class testMasterCompClient {

	private static String masterName = "TESTMASTERCOMP";
	public static void main(String[] args) throws Exception {
		Logger logger = Logger.getLogger(testMasterCompClient.class.getSimpleName());
		String managerLoc = null;
		
		managerLoc = AcsLocations.figureOutManagerLocation();
		if (managerLoc==null)
		{
			logger.severe("MANAGER_REFERENCE is missing");
			System.exit(-1);
		}
		
		ComponentClient client = new ComponentClient(logger, managerLoc, "testMasterCompClient");
		
		// get reference subsystem master:
		MasterComponent master=null; 
		if (client.getContainerServices().findComponents(masterName, null).length > 0) {
			try {
				master = MasterComponentHelper.narrow(client.getContainerServices().getComponent(masterName));
			} catch (AcsJContainerServicesEx e) {
				logger.severe(e.getContextInfo());
				//client.m_logger.severe(e.getContextInfo());
				logger.warning( "Could not connect to "+masterName+":\n"+e.toString());
			}
		} else {
			logger.warning("ERROR: Did not find component" + masterName);
			client.tearDown();
			System.exit(-1);
		}
		ROstringSeq statesProperty = master.currentStateHierarchy();

		StateChangeListener listener = new StateChangeListener(logger);		
		listener.createMonitor(statesProperty, client.getContainerServices());

		StateChangeSemaphore sync = listener.getStateChangeSemaphore();
		
		String[] actualState = listener.getCurrentState();
		logger.info(actualState[0]+"/"+actualState[1]+"/"+actualState[2]);
		
		sync.reset();
		master.doTransition(SubsystemStateEvent.SUBSYSEVENT_INITPASS1);
		sync.waitForStateChanges(2);
		
		actualState = listener.getCurrentState();
		logger.info(actualState[0]+"/"+actualState[1]+"/"+actualState[2]);
		logger.info("waiting to do something");
		Thread.sleep(10000);
		
		
		sync.reset();
		master.doTransition(SubsystemStateEvent.SUBSYSEVENT_SHUTDOWNPASS1);
		sync.waitForStateChanges(2);
		
		actualState = listener.getCurrentState();
		logger.info(actualState[0]+"/"+actualState[1]+"/"+actualState[2]);
		
		Thread.sleep(10000);
		sync.reset();
		master.doTransition(SubsystemStateEvent.SUBSYSEVENT_SHUTDOWNPASS2);
		sync.waitForStateChanges(2);
		
		actualState = listener.getCurrentState();
		logger.info(actualState[0]+"/"+actualState[1]+"/"+actualState[2]);

		client.tearDown();
	}

}
