
// ShowText.java
// Modified by Andrew Davison, ad@coe.psu.ac.th, March 2023

/* Any text that the user types appears in the window, 
   with <ENTER> causing it to be cleared.

   Uses Lanterna 3
   https://github.com/mabe02/lanterna

   More info at:
  https://stackoverflow.com/questions/68668890/print-to-the-console-while-user-is-typing

   Usage (Windows):
     > compile.bat ShowText.java
     > run.bat ShowText

   Usage (Linux):
     > ./compile.sh ShowText.java
     > ./run.sh ShowText

*/



import java.io.*;
import java.util.*;

import com.googlecode.lanterna.*;
import com.googlecode.lanterna.graphics.TextGraphics;
import com.googlecode.lanterna.input.*;
import com.googlecode.lanterna.screen.*;
import com.googlecode.lanterna.terminal.*;



public class ShowText
{

  public static void main(String[] args)
  {
    Screen scr = Utils.createScreen();
    scr.setCursorPosition(null);   // hides the cursor

    String msg = "";

    Utils.putString(scr, 5, 3, "Typed text will appear below");
    Utils.putString(scr, 3, 5, ">");
    Utils.statusLine(scr, "Press <esc> to exit...");

    KeyStroke key = Utils.readInput(scr);
    while (!Utils.hasQuit(key)) {

      if (Utils.isChar(key)) {
        if (key.getKeyType() == KeyType.Enter) {
          Utils.clearLine(scr, 5, 5, msg.length());
          msg = "";
        }
        else
          msg = msg + key.getCharacter();
        Utils.putString(scr, 5, 5, msg);
      }
      else {
        System.err.println("Not a character");
        break;
      }
      key = Utils.readInput(scr);
    }

    Utils.close(scr);
  } /* main */


}  // end of ShowText class
