package net.sourceforge.pain.network.console;
import net.sourceforge.pain.util.*;
import java.util.*;
public class BasicConsole {
protected static final int STATE_NEW = -1; //new connection
protected static final int STATE_ACTIVE = 0; // active connection
protected static final int STATE_SYSTEM_CLOSED = 1; // connection marked to be closed from system
protected static final int STATE_REMOTE_CLOSED_1 = 2; // remotely closed connection
protected static final int STATE_REMOTE_CLOSED_2 = 3; //
public static int MAX_INACTIVE_TIME = 6000; // in pulses
protected Object rawCommand = null;
protected LinkedList input = new LinkedList();
protected ConsoleAdapter adapter = null;
protected int expireTime = 0; // in net.sourceforge.pain.Pulse ticks
protected int state = STATE_NEW;
protected boolean hasBufferedOutput = false;
boolean newLineProcessingStarted = true;
protected BasicConsole (ConsoleAdapter adapter) {
this.adapter = adapter;
}
public boolean isRawMode() {
return rawCommand != null;
}
public boolean isCommandMode() {
return rawCommand == null;
}
public void setRawMode(Object rawCommand) {
this.rawCommand = rawCommand;
}
public void setCommandMode() {
rawCommand = null;
}
public Object getRawCommand() {
return rawCommand;
}
public String peekInputLine() {
if (input.isEmpty()) {
return null;
}
return (String) input.getFirst();
}
public String popInputLine() {
if (input.isEmpty()) {
return null;
}
return (String) input.removeFirst();
}
public BasicConsole out(String text) {
if (text == null) {
Log.warn("Console: out 'null'");
return this;
}
if (!hasBufferedOutput && !isRawMode() && !newLineProcessingStarted) { //new console output should starts from new line
adapterOut(ConsoleAdapter.NEW_LINE);
}
hasBufferedOutput = true;
newLineProcessingStarted = false;
adapterOut(text);
return this;
}
private void adapterOut(String text) {
if (adapter != null) {
adapter.outText(text);
}
}
public void flushOutput() {
if (!hasBufferedOutput) {
return;
}
if (adapter != null) {
try {
adapter.flush();
} catch (Exception e) {
Log.error(e.getMessage(), e); // todo: revise ignorance
}
}
hasBufferedOutput = false;
}
public void pushInputLine(String line) {
input.addFirst(line);
}
public String getRemoteAddr() {
return adapter.getRemoteAddr();
}
}