import { Output } from './output';

export class DOMOutput extends Output {

  constructor (selector) {
    super();
    let id = selector;
    if (selector[0] == '#') {
      id = selector.substring(1);
    }
    this.el = document.getElementById(id);
    this.currentLine = null;
  }

  write (text, newLine = false) {
    if (this.currentLine == null) {
      const span = document.createElement('span');
      span.classList.add('ivprog-io-output-text');
      this.el.append(span);
      this.currentLine = span;
    }
    this.currentLine.innerHTML += text;
    if (newLine) {
      this.currentLine = null;
    }
  }

  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)
          t = "&nbsp;";
        this.write(t, true);
      });
      last = last.replace(/\t/g, '&#x0020;&#x0020;');
      if (last.length != 0)
        this.write(last);
    } else {
      output = output.replace(/\t/g, '&#x0020;&#x0020;');
      this.write(output);
    }
  }

  clear () {
    this.currentLine = null;
    while(this.el.childNodes.length > 0) {
      this.el.removeChild(this.el.firstChild);
    }
  }
}