import ch.softwired.ibus.Channel;
import ch.softwired.ibus.ChannelURL;
import ch.softwired.ibus.Publisher;
import ch.softwired.ibus.ChannelViewChangeListener;
import ch.softwired.ibus.ChannelViewChangeEvent;

public class SmartStockQuoteProducer implements ChannelViewChangeListener {
	private static Object guard = new Object();
	private static boolean listenerHere = false;

	public static void main(String [] args) throws Exception {
		//There is a local counter to tag the postings
		int pushCounter = 0;
		
		//First, create the Publisher. This is the class that
		//assists with publishing events to an iBus Channel
		Publisher p = new Publisher();

		//The Publisher doesn't know yet which Channel to use
		//Its channel property needs to be set
		//So, get us a channel
		Channel blueChipsZRH = new Channel();
		
		//This channel cannot be used before setting its
		//ChannelURL property
		//So, create an URL first...
		ChannelURL url = new ChannelURL("ibus:///quotes/zrh");
		
		//...and use it to set the Channel's ChannelURL property
		blueChipsZRH.setChannelURL(url);
		
		//...and use the now working Channel to set the Publisher's
		//channel property
		p.setChannel(blueChipsZRH);
		
		//Now we need the ChannelViewChangeListener
		ChannelViewChangeListener l = new SmartStockQuoteProducer();
		blueChipsZRH.addChannelViewChangeListener(l);

		//That's it, the Publisher is now ready for use
		//Publish stock quotes now
		while(true) {
			//Don't busy wait... 
			synchronized(guard) {
				while (!listenerHere) {
					System.out.println("No listener here, going to sleep...");
					try {guard.wait();}
					catch (InterruptedException e) {}
				}
			}
			//Most probably a listener is here now
			p.publish("Quote# " + ++pushCounter + " IBM 118");
			System.out.println("Published quote# " + pushCounter);
			try {
				Thread.currentThread().sleep(1000);
			} catch(InterruptedException e) {}
		}
	}
	
	public void handleChannelViewChangeEvent(ChannelViewChangeEvent e) {
		synchronized (guard) {
			if (e.getNumListener() > 0) {
				listenerHere = true;
				guard.notifyAll();
			} else {
				listenerHere = false;
			}
		}
	}
}
