/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.cli;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Has a routine for reading a line of input from the console in a way that shouldn't block, even though it uses
 * blocking I/O calls.  That allows the reading thread to be interrupted, which we can use to support ctrl-c while
 * a user is entering input.
 *
 * This is implemented by checking {@link InputStream#available()} and then sleeping for a small interval when nothing
 * can be read.  A human shouldn't be able to detect the pause, but it's still long enough to avoid spin-locking a
 * CPU.
 */
public class InterruptibleReadline {

  private static final long MILLIS_BETWEEN_STDIN_CHECKS = 10;

  /**
   * Read a line of input from an input stream, presumably stdin.
   *
   * @param stdin An InputStream to read a line from. Note that if stdin doesn't support mark
   * (InputStream#markSupported returns true), and it is wrapped to force it to support it, then you must make sure all
   * other users or stdin use the wrapped/buffered version, or they may miss the first character after a call to
   * `readline` if '\r's appear in the stream.
   *
   * @return the string that was read, with the line terminator removed.
   *
   * @throws IOException if there was an io error reading from stdin
   * @throws InterruptedException if the thread was interrupted while waiting to receive keypresses
   */
  public static String readline(InputStream stdin) throws IOException, InterruptedException {

    // we use mark to peek ahead for \r\n
    if (!stdin.markSupported()) {
      throw new IllegalArgumentException("stdin must support mark");
    }

    // result is stored in here
    StringBuffer stringBuffer = new StringBuffer(512);
    // a byte buffer as we read a byte at a time from stdin
    byte[] bytes = new byte[64];
    // number of bytes we've read in to the buffer
    int bytesRead = 0;

    while (true) {

      // check whether read should block
      if (stdin.available() > 0) {

        int byteRead = stdin.read();

        if (byteRead == -1) {
          // end of stream - not expected for readline
          throw new EOFException();
        }

        // check for line ending character sequences, we need to detect \r, \n or \r\n
        if (byteRead == '\n') {
          // we're done!
          break;
        } else if (byteRead == '\r') {
          // we're done, but we might need to consume a trailing \n
          if (stdin.available() == 0) {
            // nothing is ready, we presume that if \r\n was sent, then they'd be sent as one and the buffer would
            // already have the \n
            // worst case, the next call to readline will exit with an empty string - if this appears to happen, we
            // could detect a \n being in stdin at the start and drop it on the floor
            break;
          } else {
            // there is a byte there - mark our position and check if it's \n
            stdin.mark(1);
            if (stdin.read() == '\n') {
              // it is we're done
              break;
            } else {
              // it isn't \n, reset position for the next call to readline or read
              stdin.reset();
              break;
            }
          }
        } else {
          bytes[bytesRead++] = (byte)byteRead;

          // flush buffer if it's full
          if (bytesRead == bytes.length) {
            stringBuffer.append(new String(bytes, 0, bytesRead));
            bytesRead = 0;
          }

        }

      } else {
        if (Thread.interrupted()) {
          throw new InterruptedException();
        } else {
          Thread.sleep(MILLIS_BETWEEN_STDIN_CHECKS);
        }
      }

    }

    stringBuffer.append(new String(bytes, 0, bytesRead));

    return stringBuffer.toString();
  }

}
