import java.io.*;

/**
 * This class attempts to erase characters echoed to the console.
 * @author Markus Hammori, modfication of code from Qusay H. Mahmoud on java.sun.com
 */
public class MaskingThread extends Thread {
    private boolean _stop = false;
    private int _refreshTime = 1; 
    private String _prompt;

    /**
     * This constructor uses the default refresh rate of 1. On slow machines you will want
     * to  set the refreshTime to a higher value  
     * @param prompt The prompt displayed to the user
     */
   public MaskingThread(String prompt) {
       this(prompt,1);
   }

    /**
     * Full constructor for the MaskingThread class.
     * @param prompt The prompt displayed to the user
     * @param refreshTime The time between the refreshing of the masking. The lower the
     * number the higher the refreshRate and the CPU usage
     */
   public MaskingThread(String prompt,int refreshTime) {
      _prompt = prompt;
      _refreshTime = refreshTime;
   }

    /**
     * Begin masking until asked to stop.
     */
    public void run() {
      while(!_stop) {
         try {
            // attempt masking at this rate
            this.sleep(_refreshTime);
         }catch (InterruptedException iex) {
            iex.printStackTrace();
         }
         if (!_stop) {
            System.out.print("\r" + _prompt + " \r" + _prompt);
         }
         System.out.flush();
      }
   }

    /**
     * Instruct the thread to stop masking.
     */
   public void stopMasking() {
      this._stop = true;
   }
}
