package terminal;

import static java.lang.Character.isDigit;
import static util.Characters.EOF;
import static util.Characters.LEFT_SQUARE_BRACKET;
import static util.Characters.UNICODE_ESCAPE;

import stream.SafeInputStream;

class ControlSequenceHandler {

    public static final boolean isEscape(char c) {
        return c == UNICODE_ESCAPE;
    }

    private ControlSequenceLookup controlSequenceLookup;
    private SafeInputStream input;
    private String code;
    private int currentCharacter;

    public ControlSequenceHandler() {
        this.controlSequenceLookup = new ControlSequenceLookup();
    }

    public ControlSequence parse(SafeInputStream inputStream) {
        input = inputStream;
        code = "";

        readCharacter();
        if (isExpectedFirstCharacter())
            readCode();

        return controlSequenceLookup.get((char) currentCharacter, code);
    }

    private void readCharacter() {
        currentCharacter = input.read();
    }

    private boolean isExpectedFirstCharacter() {
        return isCharacter() && isLeftBracket();
    }

    private boolean isCharacter() {
        return currentCharacter != EOF;
    }

    private boolean isLeftBracket() {
        return (char) currentCharacter == LEFT_SQUARE_BRACKET;
    }

    private void readCode() {
        for (readCharacter(); isPartOfCode(); readCharacter())
            code += (char) currentCharacter;
    }

    private boolean isPartOfCode() {
        return isCharacter() && isDigit((char) currentCharacter);
    }

}
