const BACKSPACE = 8;
const COMMA = 44;
const ENTER = 13;
const SPACE = 32;

export default class WsInputPillsController {
  static $inject = [
    '$document',
  ];

  constructor($document) {
    this.$document = $document;
  }

  $onInit() {
    this.pills = [];
    this.pillInput = null;
    this.initialPlaceholderText = this.placeholderText;
    this.dismissText = this.dismissText || 'x';
  }

  focusInput() {
    this.$document[0].querySelector('.ws-input-pills__input').focus();
  }

  keydownHandler(event) {
    if ([BACKSPACE].includes(event.which) && !this.pillInput) {
      this._removeLastPill();
      this.onModelChange({ pills: this.pills, pillInput: this.pillInput });

      if (this.pills.length === 0) {
        this._setPlaceholder();
      }
    }
  }

  keypressHandler(event) {
    if ([COMMA, ENTER, SPACE].includes(event.which)) {
      if (this.pillInput) {
        this._addPill(this.pillInput);
        this._clearInput();
        this.onModelChange({ pills: this.pills, pillInput: this.pillInput });
      }

      event.preventDefault();
    }
  }

  removePill(pill) {
    this.pills = this.pills.filter(existingPill => existingPill !== pill);

    if (this.pills.length === 0) {
      this._setPlaceholder();
    }
  }

  _addPill(input) {
    this.pills = this.pills.filter(pill => pill !== input);
    this.pills.push(input);
  }

  _removeLastPill() {
    this.pills.pop();
  }

  _clearInput() {
    this.pillInput = null;
    this.placeholderText = null;
  }

  _setPlaceholder() {
    this.placeholderText = this.initialPlaceholderText;
  }
}
