/* 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];
  private int sp = 0;
  private KeyEvent old = null;
    
  public ConsoleReader(FrameConsole fc) {
    this.fc = fc;
    if ( !fc.open )
      fc.ouvre();
  }

  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 void keyPressed(KeyEvent e) {
  }
  
  public void keyReleased(KeyEvent e) {
  }
  
  public void keyTyped(KeyEvent e) {
    if ( old != e ) {
      old = e;
      char code = e.getKeyChar();
      if ( ( code >= 32 ) || ( code == 10 ) || ( code == 8 ) ) {
        buffer[sp] = code;
        sp++; } }
  }
}