package commons.ui;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CommandInputReader extends Reader implements KeyListener
{

Object          mKeyLock     = new Object();
Object          mLineLock    = new Object();
String          mLastLine;
int             mLastKeyCode = 1;
UIController    ic           = null;
ExecutorService executor     = Executors.newFixedThreadPool(2);

public CommandInputReader(UIController ic)
{
   this.ic = ic;
}

public void start ()
{
   executor.execute(new Runnable()
   {

      public void run ()
      {
         while (!ic.exit())
         {
            read();
         }
      }
   });
   executor.execute(new Runnable()
   {

      public void run ()
      {
         while (!ic.exit())
         {
            String input = readLine();
            ic.eval(input);
            ic.print("\n");
         }
      }
   });
}

public String readLine ()
{
   synchronized (mLineLock)
   {
      try
      {
         mLineLock.wait();
      }
      catch (InterruptedException ex)
      {}
   }
   return mLastLine;
}

public int read ()
{
   synchronized (mKeyLock)
   {
      try
      {
         mKeyLock.wait();
      }
      catch (InterruptedException ex)
      {}
   }
   return mLastKeyCode;
}

public void keyPressed (KeyEvent ke)
{
   // synchronized(mKeyLock) {
   mLastKeyCode = ke.getKeyCode();
   synchronized (mKeyLock)
   {
      mKeyLock.notifyAll();
   }
   // }
   if (ke.getKeyCode() == 27) ic.clearInput();
   else if (ke.getKeyCode() == KeyEvent.VK_ENTER)
   {
      mLastLine = ic.getInput();
      synchronized (mLineLock)
      {
         mLineLock.notifyAll();
      }
   }
}

public void keyReleased (KeyEvent ke)
{}

public void keyTyped (KeyEvent ke)
{}

public void close () throws IOException
{}

public int read (char[] arg0, int arg1, int arg2) throws IOException
{
   throw new IOException("Not supported");
}
}
