// Generated by CoffeeScript 1.7.1
(function() {
  var colors,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  window.Controls.terminal__thumbnail = (function(_super) {
    __extends(terminal__thumbnail, _super);

    function terminal__thumbnail() {
      return terminal__thumbnail.__super__.constructor.apply(this, arguments);
    }

    terminal__thumbnail.prototype.createDom = function() {
      return "<div class=\"control terminal-thumbnail\">\n    <img src=\"/ajenti:terminal/" + this.properties.tid + "/thumbnail\" />\n    <a class=\"close\">&#x2715;</a>\n</div>";
    };

    terminal__thumbnail.prototype.setupDom = function(dom) {
      terminal__thumbnail.__super__.setupDom.call(this, dom);
      $(this.dom).click((function(_this) {
        return function() {
          return Tabs.addTab("/ajenti:terminal/" + _this.properties.tid, "Terminal " + _this.properties.tid);
        };
      })(this));
      return $(this.dom).find('a').click((function(_this) {
        return function(e) {
          _this.event('close');
          return e.stopPropagation();
        };
      })(this));
    };

    return terminal__thumbnail;

  })(window.Control);

  colors = {
    black: '#000000',
    green: '#859900',
    white: '#eee8d5',
    yellow: '#b58900',
    red: '#dc322f',
    magenta: '#d33682',
    violet: '#6c71c4',
    blue: '#268bd2',
    cyan: '#2aa198'
  };

  window.Terminal = (function() {
    function Terminal() {
      this.send = __bind(this.send, this);
      this.select = __bind(this.select, this);
      this.id = document.location.href.split('/')[4];
      this.term = $('#term');
      this.socket = ajentiConnectSocket('/terminal');
      $(document).keydown((function(_this) {
        return function(event) {
          if ([8, 37, 38, 39, 40].indexOf(event.keyCode) > -1) {
            return event.preventDefault();
          }
        };
      })(this));
      $(document).keypress((function(_this) {
        return function(event) {
          var ch;
          ch = _this.filter_key(event, !!(/Firefox/.exec(navigator.userAgent)));
          if (event.which !== 13 && event.which !== 8) {
            _this.send(RawDeflate.Base64.encode(ch));
          }
          return event.preventDefault();
        };
      })(this));
      $(document).keyup((function(_this) {
        return function(event) {
          var ch;
          ch = _this.filter_key(event);
          _this.send(RawDeflate.Base64.encode(ch));
          return event.preventDefault();
        };
      })(this));
      this.socket.on('connect', function() {
        return console.log('Terminal connected');
      });
      this.socket.on('set', (function(_this) {
        return function(data) {
          Loading.hide();
          _this.draw(data);
          return _this.socket.send(JSON.stringify({
            type: 'read'
          }));
        };
      })(this));
      this.socket.on('re-select', (function(_this) {
        return function(data) {
          return _this.select();
        };
      })(this));
    }

    Terminal.prototype.select = function() {
      return this.socket.send(JSON.stringify({
        type: 'select',
        tid: this.id
      }));
    };

    Terminal.prototype.send = function(ch) {
      if (ch) {
        return this.socket.send(JSON.stringify({
          type: 'key',
          key: ch,
          tid: this.id
        }));
      }
    };

    Terminal.prototype.draw = function(data) {
      var k, lns, _results;
      data = RawDeflate.inflate(RawDeflate.Base64.decode(data));
      console.log('Payload size', data.length);
      data = JSON.parse(data);
      console.log('Payload', data);
      $('#term pre.cursor').removeClass('cursor');
      this.cursor = data.cursor;
      if (data.cursor) {
        this.cursx = data.cx;
        this.cursy = data.cy;
      } else {
        this.cursx = -1;
      }
      lns = $('#term div');
      _results = [];
      for (k in data.lines) {
        _results.push((function(_this) {
          return function(k) {
            var ln;
            if (lns.length <= k) {
              return $('#term').append(_this.row(data.lines[k], k));
            } else {
              ln = $(lns[k]);
              return ln.html(_this.cells(data.lines[k], k));
            }
          };
        })(this)(k));
      }
      return _results;
    };

    Terminal.prototype.row = function(row, idx) {
      return '<div>' + this.cells(row, idx) + '</div>';
    };

    Terminal.prototype.cells = function(row, idx) {
      var background, bg, bold, cell, ch, color, fg, i, iidx, it, misc, r, sty, und, _i, _ref;
      r = '<pre>';
      fg = 0;
      bg = 0;
      bold = 0;
      it = 0;
      und = 0;
      for (i = _i = 0, _ref = row.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        cell = row[i];
        iidx = parseInt(idx);
        if (i === 0 || bg !== cell[2] || fg !== cell[1] || bold !== cell[3] || (iidx === this.cursy && i === this.cursx) || (iidx === this.cursy && i === this.cursx + 1)) {
          misc = '';
          sty = '';
          if (iidx === this.cursy && i === this.cursx) {
            misc = ' class="cursor" ';
          }
          if (cell[3]) {
            sty += 'font-weight: bold;';
          }
          if (cell[4]) {
            sty += 'font-style: italic;';
          }
          if (cell[5]) {
            sty += 'text-decoration: underline;';
          }
          color = cell[1];
          if (color === 'default') {
            color = 'white';
          }
          color = colors[color];
          if (color == null) {
            color = cell[1];
          }
          background = cell[2];
          if (background === 'default') {
            background = 'black';
          }
          background = colors[background];
          if (background == null) {
            background = cell[2];
          }
          r += '</pre><pre' + misc + ' style="color:' + color + ';background:' + background + ';' + sty + '">';
          fg = cell[1];
          bg = cell[2];
          bold = cell[3];
          it = cell[4];
          und = cell[5];
        }
        ch = cell[0];
        if (ch === '<') {
          ch = '&lt';
        }
        if (ch === '>') {
          ch = '&gt';
        }
        r += cell[0];
      }
      r += '</pre>';
      return r;
    };

    Terminal.prototype.filter_key = function(event, ign_arrows) {
      var ch;
      ch = event.charCode;
      if (event.ctrlKey) {
        ch = String.fromCharCode(event.keyCode - 64);
        return ch;
      }
      if (!ch && event.keyCode >= 112 && event.keyCode <= 123) {
        ch = '\x1b' + (event.keyCode - 111);
        return ch;
      }
      if (ch) {
        if (event.ctrlKey) {
          ch = String.fromCharCode(ch - 96);
        } else {
          ch = String.fromCharCode(ch);
          if (ch === '\r') {
            ch = '\n';
          }
        }
      } else {
        switch (event.keyCode) {
          case 8:
            ch = '\b';
            break;
          case 9:
            if (!ign_arrows) {
              ch = '\t';
            }
            break;
          case 13:
          case 10:
            ch = '\r';
            break;
          case 38:
            if (!ign_arrows) {
              ch = '\x1b[A';
            }
            break;
          case 40:
            if (!ign_arrows) {
              ch = '\x1b[B';
            }
            break;
          case 39:
            if (!ign_arrows) {
              ch = '\x1b[C';
            }
            break;
          case 37:
            if (!ign_arrows) {
              ch = '\x1b[D';
            }
            break;
          case 46:
            ch = '\x1b[3~';
            break;
          case 35:
            ch = '\x1b[F';
            break;
          case 36:
            ch = '\x1b[H';
            break;
          case 34:
            ch = '\x1b[6~';
            break;
          case 33:
            ch = '\x1b[5~';
            break;
          case 27:
            ch = '\x1b';
            break;
          default:
            return '';
        }
      }
      event.preventDefault();
      return ch;
    };

    return Terminal;

  })();

}).call(this);
