ig.module(
    'game.entities.namefield'
)
.requires(
    'impact.entity'
)
.defines(function() {
  EntityNameField = ig.Entity.extend({
    font: new ig.Font('media/lcddot.grey.font.png'),
    fontActiveChar: new ig.Font('media/lcddot.font.png'),
    activeCharArrows: new ig.Image('media/lcddot.arrows.png'),

    symbols: ['_', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
    numberOfChars: 3,
    highlightedChar: 0,
    _name: [1, 0, 0],

    init: function(x, y, settings) {
      this.parent(x, y, settings);

      ig.input.bind(ig.KEY.RIGHT_ARROW, 'next-char');
      ig.input.bind(ig.KEY.LEFT_ARROW, 'prev-char');
      ig.input.bind(ig.KEY.UP_ARROW, 'next-symbol');
      ig.input.bind(ig.KEY.DOWN_ARROW, 'prev-symbol');

      // VIM goodness
      ig.input.bind(ig.KEY.H, 'prev-char');
      ig.input.bind(ig.KEY.J, 'prev-symbol');
      ig.input.bind(ig.KEY.K, 'next-symbol');
      ig.input.bind(ig.KEY.L, 'next-char');
    },

    update: function() {
      // Switch chars
      if (ig.input.pressed('prev-char') && this.highlightedChar > 0) {
        this.highlightedChar--;
      }
      if (ig.input.pressed('next-char') && this.highlightedChar < this.numberOfChars-1)
        this.highlightedChar++;

      // Switch symbols
      if (ig.input.pressed('prev-symbol')) {
        this._name[this.highlightedChar]--;
        if  (this._name[this.highlightedChar] < 0)
          this._name[this.highlightedChar] = this.symbols.length-1;
      }
      if (ig.input.pressed('next-symbol')) {
        this._name[this.highlightedChar]++;
        if (this._name[this.highlightedChar] == this.symbols.length)
          this._name[this.highlightedChar] = 0;
      }

      this.parent();
    },

    draw: function() {
      this.parent();
      for(var i=0; i<this.numberOfChars; i++) {
        var symbol = this.symbols[this._name[i]];
        var x = 20 + this.pos.x + 40*i + 5;
        var y = 20 + this.pos.y;

        if (i == this.highlightedChar) {
          this.fontActiveChar.draw(symbol, x, y, ig.Font.ALIGN.CENTER);
          this.activeCharArrows.draw(x-15, y-22);
        } else {
          this.font.draw(symbol, x, y, ig.Font.ALIGN.CENTER);
        }
      }
    },

    name: function() {
      var name = '';
      for(var i=0; i<this.numberOfChars; i++)
        name += this.symbols[this._name[i]];
      return name;
    }
  });
});
