
import java.util.*;


public class DemoApp implements Tickable, KeyboardListener {

    private TimerThread timer;
    private BlockingQueue work;

    private static boolean verbose = false;


    // constructor

    public DemoApp () {
        work = new BlockingQueue ();    
    }


    // addWork - add generic QMsg to our work queue

    public void addWork (QMsg o) {
        work.add (o);
    }

    // KeyboardListener interface methods
    // newKeyboardLine - add a new text message to our work queue

    public void newKeyboardLine (String msg) {
        addWork (new QMsg (msg, QMsg.NORMAL));
    }


    // Tickable interface methods -- called by timer thread

    public void tick () {
        addWork (new QMsg ("", QMsg.WAKEUP));
    }


    // our main loop

    private void run () {

        // start a timer that wakes us up every 10 seconds

        timer = new TimerThread (this, 10000);
        timer.start ();

        // start a keyboard reader thread

        KeyboardThread k = new KeyboardThread (this);
        k.start ();

        // process work requests as they come in

        while (true) {
            process ();
        }
    }


    // process - handle items on our work queue

    private void process() {

        while (true) {

            // wait for something to do

            QMsg qmsg = (QMsg)work.remove ();
            if (qmsg == null) {
                System.out.println ("QMsg was null");
                return;
            }

            // get the flags out of the queue message
                
            int flags = qmsg.getFlags();

            if (flags == QMsg.QUIT) {
                System.out.println ("Quit received");
                System.exit (0);
            } else if (flags == QMsg.WAKEUP) {
                System.out.println ("Wakeup received");
            } else if (flags == QMsg.NORMAL) {
                String msg = (String)qmsg.getPayload();
                System.out.println ("New text message: " + msg);
            } else {
                System.out.println ("flags: " + flags + ", payload: '" + qmsg.getPayload().toString() + "'");
            }
        }
    }

 
    // parseArgs - parse the command line arguments

    private static void parseArgs(String[] args) {

        for (int i = 0; i < args.length; i++) {
            String arg = args[i++];
	      if (arg.equals("-v")) {
		    verbose = true;
	      } else 
		    System.err.println("Unknown option " + arg);
	  } 
    }


    // main

    public static void main (String[] args) {

        parseArgs(args);
        DemoApp app = new DemoApp ();
        app.run ();
    }

}
