/**
 * 
 */
package astri.test.testPingComp1Impl;

import java.util.logging.Logger;

import alma.JavaContainerError.wrappers.AcsJContainerServicesEx;
import alma.acs.component.client.ComponentClient;
import alma.acs.container.ContainerServices;
import alma.acs.nc.AcsEventSubscriber;
import alma.acs.nc.AcsEventSubscriber.Callback;
import alma.acs.util.AcsLocations;
import alma.acsnc.EventDescription;
import astri.test.testPingComp1;
import astri.test.testPingComp1Package.testPingCompNotificationEvent;

/**
 * @author astrisw
 *
 */
public class testPingCompClient implements Callback<testPingCompNotificationEvent>{


	private static ContainerServices m_containerServices =null;;
	private static AcsEventSubscriber<testPingCompNotificationEvent> m_subscriber = null;
	private static ComponentClient m_client = null;
	private static Logger m_logger = null;
	private volatile int received = 0;
	public testPingCompClient() {

		m_logger = Logger.getLogger(testPingCompClient.class.getSimpleName());
		String managerLoc = null;
		
		managerLoc = AcsLocations.figureOutManagerLocation();
		if (managerLoc==null)
		{
			m_logger.severe("MANAGER_REFERENCE is missing");
			System.exit(-1);
		}
		
		try {
			m_client  = new ComponentClient(m_logger, managerLoc, "testPingCompClient");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		m_containerServices = m_client.getContainerServices();
	}
	
	public void createSubscriber() {
		try {
			m_subscriber = m_containerServices.createNotificationChannelSubscriber(testPingComp1.CHANNELNAME_TEST,testPingCompNotificationEvent.class);
		} catch (AcsJContainerServicesEx e) {
			e.printStackTrace();
		}
	}
	
	public void startReceiving() throws Exception {
		m_subscriber.addSubscription(this);
		m_subscriber.startReceivingEvents();
	}
	
	public void close() throws Exception {
		m_subscriber.disconnect();
		m_client.tearDown();
		m_logger.info("Received " + received + " events");
	}

	@Override
	public void receive(testPingCompNotificationEvent event, EventDescription eventDescrip) {
		received++;
		m_containerServices.getThreadFactory().newThread(new Runnable() {
			@Override
			public void run() {
				processEvent(event);
			}
		}).start();
		
	}

	@Override
	public Class<testPingCompNotificationEvent> getEventType() {
		
		return testPingCompNotificationEvent.class;
	}
	
	public void processEvent (testPingCompNotificationEvent event) {
		String timestamp = event.timestamp;
		String msgT = event.msgtype;
		String txt =event.txt;
    	m_logger.info("Received Event ("+received+")"+timestamp+":"+msgT+":"+txt);
	}
	
	
	public static void main(String[] args) {
		
		
		testPingCompClient client = new testPingCompClient();
		
		client.createSubscriber();
		
		try {
			client.startReceiving();
			Thread.sleep(30000);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		try {
			client.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}

	

}
