/* Auteur: Nicolas JANEY          */
/* nicolas.janey@univ-fcomte.fr   */
/* Fevrier 2005                   */

import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class ConsoleReader implements KeyListener {
  public FrameConsole fc;
  private static char [] buffer = new char[1000];
  public int sp = 0;
    
  public ConsoleReader(FrameConsole fc) {
    this.fc = fc;
    if ( !fc.open )
      fc.ouvre();
    Console.setKeyListeners();
  }

  public String readLine() {
    Console.setKeyListeners();
    Console.line = new String();
    String s = new String();
    boolean ok = false;
    while ( !ok ) {
      try {
        Thread.sleep(30);
        if ( sp != 0 ) {
          switch ( ((int) buffer[0]) ) {
            case  10 : ok = true;
                       break;
            case   8 : if ( s.length() > 0 ) {
                         s = s.substring(0,s.length()-1);
                         Console.line = s;
                         Console.fc.cc.repaint(); }
                       break;
            default  : s += buffer[0];
                       Console.line = s;
                       Console.fc.cc.repaint();
                       break; }
          for ( int i = 0 ; i < sp-1 ; i++ )
            buffer[i] = buffer[i+1];
          sp--; } }
      catch (InterruptedException e) { } }
    Console.line = new String();
    Console.fc.cc.print(s+"\n");
    return(s);
  }

  public char read() {
    Console.setKeyListeners();
    if ( sp != 0 ) {
      Console.line = new String();
      Console.fc.cc.print(buffer[0]+"\n");
      sp = 0;
      return(buffer[0]); }
      else
      return(0x0000);
  }

  public void keyPressed(KeyEvent e) {
    if ( !e.isConsumed() ) {
      e.consume(); }
  }
  
  public void keyReleased(KeyEvent e) {
    if ( !e.isConsumed() ) {
      e.consume(); }
  }
  
  public void keyTyped(KeyEvent e) {
    if ( !e.isConsumed() ) {
      e.consume();
      char code = e.getKeyChar();
      if ( ( code >= 32 ) || ( code == 10 ) || ( code == 8 ) ) {
        buffer[sp] = code;
        sp++; } }
  }
}