import pencilIcon from '../../assets/pencil.svg';

AutoGrowInputDirective.$inject = ['autogrowInputService'];

export default function AutoGrowInputDirective(autogrowInputService) {
  const { keyTypeForEventIs, setInputWidth } = autogrowInputService;

  return {
    require: '?ngModel',
    restrict: 'A',
    link,
  };

  function link(scope, element, attrs, ngModelCtrl) {
    element.addClass('autogrow-input');
    scope.$watch(() => ngModelCtrl.$modelValue, (newVal) => {
      setInputWidth(newVal, element);
    });

    initPencilIndicator(scope, element, attrs);
    initInputListener(scope, element, attrs);
  }

  function initPencilIndicator(scope, element, attrs) {
    if (angular.isDefined(attrs.showPencil)) {
      const inputField = angular.element(element);
      const pencilIndicator = angular.element(`<a href="javascript:void(0);" class="pencil-indicator">${pencilIcon}</a>`);

      pencilIndicator.on('click', () => {
        inputField.focus();
        inputField.select();
      });

      angular.element(element).after(pencilIndicator);
    }
  }

  function initInputListener(scope, element, attrs) {
    element.on('keydown', (e) => {
      let expectedVal;

      if (keyTypeForEventIs('backspace', e)) {
        expectedVal = angular.element(element).val().slice(0, -1);
      } else if (keyTypeForEventIs('letter', e) || keyTypeForEventIs('number', e)) {
        if (attrs.type === 'number' && !keyTypeForEventIs('number', e)) {
          return;
        }

        const key = e.which || e.keyCode || 0;
        expectedVal = angular.element(element).val() + String.fromCharCode(key);
      } else {
        return;
      }

      setInputWidth(expectedVal, element);
    });
  }
}
