import { DOMConsole } from "../io/domConsole";
import { getInstance } from "../services/localizedStringsService";

const LocalizedStrings = getInstance();

export class TestConsole {


  constructor (inputList) {
    this.index = 0;
    this.inputList = inputList;
    this.list = [];
    this.currentLine = null;
  }

  writeRawHTML (text) {
    this._appendTextLn(text);
  }
  write (text, newLine = false) {
    this._appendText(text, DOMConsole.USER, newLine);
  }

  info (text) {
    this._appendTextLn(text, DOMConsole.INFO);
  }

  err (text) {
    this._appendTextLn(text, DOMConsole.ERR);
  }

  _appendText (text, _type, newLine = false) {
    if (this.currentLine == null) {
      this.currentLine = this.list.push('') - 1;
    }

    this.list[this.currentLine] += text;
    if (newLine) {
      this.currentLine = null;
    }
  }

  _appendTextLn (text) {
    this.list.push(text);
    this.currentLine = null;
  }

  getClassForType (type) {
    switch (type) {
      case DOMConsole.USER:
        return "ivprog-term-userText";
      case DOMConsole.INFO:
        return "ivprog-term-info";
      case DOMConsole.ERR:
        return "ivprog-term-error";
    }
  }

  requestInput () {
    const promise = new Promise( (resolve, reject) => {
      if(this.index < this.inputList.length) {
        resolve(this.inputList[this.index]);
        this.index++;
      } else {
        reject(new Error(LocalizedStrings.getError("exceeded_input_request")));
      }
    });
    return promise
  }

  sendOutput (text) {
    let output = '' + text;
    if (output.indexOf('\n') !== -1) {
      const outputList = output.split('\n');
      let last = outputList.pop();
      outputList.forEach( t => {
        t = t.replace(/\t/g, '&#x0020;&#x0020;');
        t = t.replace(/\s/g, "&#x0020;");
        if (t.length == 0)
          this.currentLine = null;
        else
          this.write(t, true);
      });
      last = last.replace(/\t/g, '&#x0020;&#x0020;');
      last = last.replace(/\s/g, "&#x0020;");
      if (last.length != 0)
        this.write(last);
    } else {
      output = output.replace(/\t/g, '&#x0020;&#x0020;');
      output = output.replace(/\s/g, "&#x0020;");
      this.write(output);
    }
  }
}