"use strict";
//Written by HairyOtter07, converted from Python to Javscript by Prince Komali
class BrainFParser {
    constructor(text) {
        this.text = text;
        if(!this.text.endsWith("!")) this.text += "!";
        this.input = this.parse_input();
        this.pos = 0;
        this.char = this.text[this.pos];
        this.cells = new Array(30000).fill(0);
        this.pointer = 0;
        this.input_index = 0;
        this.buffer = "";
        this.loop_indices = [];
        this.skipping = false;
    }
    
    parse_input() {
        var result = "";
        var index = this.text.indexOf("!") + 1;
        while (index <= this.text.length - 1) {
            result += this.text[index];
            index += 1;
        }
        return result
    }
    advance() {
        
        this.pos += 1;
        if (this.pos > this.text.length - 1) {
            throw new Error("Invalid Code");
        }
        else {
            this.char = this.text[this.pos];
        }
    }
    parse() {
        let start = new Date();
        while (this.char != "!"){
            if(new Date() - start >= 5000) {
                throw new Error("Timed out")
            }
            if(this.char == "!") return;
            if (this.char == "[" && this.cells[this.pointer] != 0) {
             
                this.loop_indices.push(this.pos);
            } else if (this.char == "[") {
               
                this.skipping = true;
            } else if (this.char == "]" && this.cells[this.pointer] != 0 ) {
               
               
               
               this.pos = this.loop_indices[this.loop_indices.length -1];
                this.char = this.text[this.pos];
               
            } else if (this.char == "]" && this.skipping) {
                this.skipping = false;
                continue;
            } else if (this.char == "]") {
                this.loop_indices.pop();
            } else if (this.skipping) {
               
                this.advance();
                continue;
            } else if (this.char == "+") {
                
                this.cells[this.pointer] += 1;
            } else if (this.char == "-") {
                this.cells[this.pointer] -= 1;
            } else if (this.char == ">") {
                this.pointer += 1;
            } else if (this.char == "<") {
                this.pointer -= 1;
            } else if (this.char == ".") {
                this.buffer += String.fromCharCode(this.cells[this.pointer]);
            } else if (this.char == ",") {
                this.cells[this.pointer] = (this.input[this.input_index]).charCodeAt(0);
                this.input_index += 1;
               
            }
            this.advance();
        }
            return this.buffer;
        
    }
}
module.exports = BrainFParser;