export default class WsMultipleInputController {
  $onInit() {
    this.inputCount = parseInt(this.numberOfInputs, 10);
    this.model = {
      inputs: [],
    };
  }

  range = n => new Array(n);

  onKeyUp = ($event) => {
    if (!this.isReadonly) {
      // When maximum length is reached for current input
      if ($event.target.value.length === $event.target.maxLength) {
        const inputs = this.model.inputs;
        const populated = inputs.filter(input => angular.isString(input) && input.length > 0);
        // If all inputs have been populated, calls onCompleted
        // Otherwise, move to next input
        if (populated.length === this.inputCount) {
          const finalInput = inputs.join('');
          this.onCompleted(finalInput);
        } else if ($event.target.nextElementSibling !== null) {
          $event.target.nextElementSibling.focus();
        }
      }
    }
  };

  onKeyDown = ($event) => {
    if (!this.isReadonly) {
      // When trying to delete from an empty input, delete from the previous one
      if (($event.target.value.length === 0) && ($event.key === 'Backspace')) {
        if ($event.target.previousElementSibling !== null) {
          $event.target.previousElementSibling.focus();
        }
      }
    }
  };
}
