// Generated by CoffeeScript 1.9.3
var Block, SpecialString, cloneAndMergeDeep, terminalWidth;

SpecialString = require('./SpecialString');

terminalWidth = require('../tools').getCols();

cloneAndMergeDeep = require('../tools').cloneAndMergeDeep;

module.exports = Block = (function() {
  var self;

  self = Block;

  Block.defaultConfig = {
    blockPrependor: {
      fn: require('./block/blockPrependor/Default'),
      options: {
        amount: 0
      }
    },
    blockAppendor: {
      fn: require('./block/blockAppendor/Default'),
      options: {
        amount: 0
      }
    },
    linePrependor: {
      fn: require('./block/linePrependor/Default'),
      options: {
        amount: 0
      }
    },
    lineAppendor: {
      fn: require('./block/lineAppendor/Default'),
      options: {
        amount: 0
      }
    },
    lineWrapper: {
      fn: require('./block/lineWrapper/Default'),
      options: {
        lineWidth: null
      }
    },
    width: terminalWidth,
    prefixRaw: '',
    suffixRaw: ''
  };

  function Block(_layout, _parent, config, _name) {
    this._layout = _layout;
    this._parent = _parent;
    if (config == null) {
      config = {};
    }
    this._name = _name != null ? _name : '';
    this._config = cloneAndMergeDeep(self.defaultConfig, config);
    this._closed = false;
    this._wasOpenOnce = false;
    this._active = false;
    this._buffer = '';
    this._didSeparateBlock = false;
    this._linePrependor = new this._config.linePrependor.fn(this._config.linePrependor.options);
    this._lineAppendor = new this._config.lineAppendor.fn(this._config.lineAppendor.options);
    this._blockPrependor = new this._config.blockPrependor.fn(this._config.blockPrependor.options);
    this._blockAppendor = new this._config.blockAppendor.fn(this._config.blockAppendor.options);
  }

  Block.prototype._activate = function(deactivateParent) {
    if (deactivateParent == null) {
      deactivateParent = true;
    }
    if (this._active) {
      throw Error("This block is already active. This is probably a bug in RenderKid itself");
    }
    if (this._closed) {
      throw Error("This block is closed and cannot be activated. This is probably a bug in RenderKid itself");
    }
    this._active = true;
    this._layout._activeBlock = this;
    if (deactivateParent) {
      if (this._parent != null) {
        this._parent._deactivate(false);
      }
    }
    return this;
  };

  Block.prototype._deactivate = function(activateParent) {
    if (activateParent == null) {
      activateParent = true;
    }
    this._ensureActive();
    this._flushBuffer();
    if (activateParent) {
      if (this._parent != null) {
        this._parent._activate(false);
      }
    }
    this._active = false;
    return this;
  };

  Block.prototype._ensureActive = function() {
    if (!this._wasOpenOnce) {
      throw Error("This block has never been open before. This is probably a bug in RenderKid itself.");
    }
    if (!this._active) {
      throw Error("This block is not active. This is probably a bug in RenderKid itself.");
    }
    if (this._closed) {
      throw Error("This block is already closed. This is probably a bug in RenderKid itself.");
    }
  };

  Block.prototype._open = function() {
    if (this._wasOpenOnce) {
      throw Error("Block._open() has been called twice. This is probably a RenderKid bug.");
    }
    this._wasOpenOnce = true;
    if (this._parent != null) {
      this._parent.write(this._whatToPrependToBlock());
    }
    this._activate();
    return this;
  };

  Block.prototype.close = function() {
    this._deactivate();
    this._closed = true;
    if (this._parent != null) {
      this._parent.write(this._whatToAppendToBlock());
    }
    return this;
  };

  Block.prototype.isOpen = function() {
    return this._wasOpenOnce && !this._closed;
  };

  Block.prototype.write = function(str) {
    this._ensureActive();
    if (str === '') {
      return;
    }
    str = String(str);
    this._buffer += str;
    return this;
  };

  Block.prototype.openBlock = function(config, name) {
    var block;
    this._ensureActive();
    block = new Block(this._layout, this, config, name);
    block._open();
    return block;
  };

  Block.prototype._flushBuffer = function() {
    var str;
    if (this._buffer === '') {
      return;
    }
    str = this._buffer;
    this._buffer = '';
    this._writeInline(str);
  };

  Block.prototype._toPrependToLine = function() {
    var fromParent;
    fromParent = '';
    if (this._parent != null) {
      fromParent = this._parent._toPrependToLine();
    }
    return this._linePrependor.render(fromParent);
  };

  Block.prototype._toAppendToLine = function() {
    var fromParent;
    fromParent = '';
    if (this._parent != null) {
      fromParent = this._parent._toAppendToLine();
    }
    return this._lineAppendor.render(fromParent);
  };

  Block.prototype._whatToPrependToBlock = function() {
    return this._blockPrependor.render();
  };

  Block.prototype._whatToAppendToBlock = function() {
    return this._blockAppendor.render();
  };

  Block.prototype._writeInline = function(str) {
    var i, j, k, l, lineBreaksToAppend, m, ref, ref1, ref2, remaining;
    if (SpecialString(str).isOnlySpecialChars()) {
      this._layout._append(str);
      return;
    }
    remaining = str;
    lineBreaksToAppend = 0;
    if (m = remaining.match(/^\n+/)) {
      for (i = j = 1, ref = m[0].length; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
        this._writeLine('');
      }
      remaining = remaining.substr(m[0].length, remaining.length);
    }
    if (m = remaining.match(/\n+$/)) {
      lineBreaksToAppend = m[0].length;
      remaining = remaining.substr(0, remaining.length - m[0].length);
    }
    while (remaining.length > 0) {
      if (m = remaining.match(/^[^\n]+/)) {
        this._writeLine(m[0]);
        remaining = remaining.substr(m[0].length, remaining.length);
      } else if (m = remaining.match(/^\n+/)) {
        for (i = k = 1, ref1 = m[0].length; 1 <= ref1 ? k < ref1 : k > ref1; i = 1 <= ref1 ? ++k : --k) {
          this._writeLine('');
        }
        remaining = remaining.substr(m[0].length, remaining.length);
      }
    }
    if (lineBreaksToAppend > 0) {
      for (i = l = 1, ref2 = lineBreaksToAppend; 1 <= ref2 ? l <= ref2 : l >= ref2; i = 1 <= ref2 ? ++l : --l) {
        this._writeLine('');
      }
    }
  };

  Block.prototype._writeLine = function(str) {
    var line, lineContent, lineContentLength, remaining, roomLeft, toAppend, toAppendLength, toPrepend, toPrependLength;
    remaining = SpecialString(str);
    while (true) {
      toPrepend = this._toPrependToLine();
      toPrependLength = SpecialString(toPrepend).length;
      toAppend = this._toAppendToLine();
      toAppendLength = SpecialString(toAppend).length;
      roomLeft = this._layout._config.terminalWidth - (toPrependLength + toAppendLength);
      lineContentLength = Math.min(this._config.width, roomLeft);
      lineContent = remaining.cut(0, lineContentLength, true);
      line = toPrepend + lineContent.str + toAppend;
      this._layout._appendLine(line);
      if (remaining.isEmpty()) {
        break;
      }
    }
  };

  return Block;

})();
