export default function AutoGrowInputService() {
  return {
    setInputWidth,
    getTextWidth,
    getFontStyles,
    keyTypeForEventIs,
  };

  function setInputWidth(text, input) {
    const newWidth = getTextWidth(text, input) + 1;
    input.css('width', `${newWidth}px`);
  }

  function getTextWidth(text, input) {
    const fontStyles = getFontStyles(input);
    const ghostStyles = Object.assign({ border: '1px solid yellow' }, fontStyles);
    const ghostElement = angular.element('<span></span>').text(text).addClass('ghost-element').css(ghostStyles);
    input.after(ghostElement);
    const width = ghostElement[0].offsetWidth;
    ghostElement.remove();
    return width;
  }

  function getFontStyles(input) {
    return {
      'font-size': getComputedStyle(angular.element(input)[0])['font-size'],
      'font-family': getComputedStyle(angular.element(input)[0])['font-family'],
      'font-weight': getComputedStyle(angular.element(input)[0])['font-weight'],
      'font-style': getComputedStyle(angular.element(input)[0])['font-style'],
    };
  }

  function keyTypeForEventIs(type, e) {
    const keyCode = e.which || e.keyCode || 0;

    if (type === 'number' && (keyCode >= 48 && keyCode <= 57)) {
      return true;
    } else if (type === 'letter' && ((keyCode >= 65 && keyCode <= 90) || keyCode === 32)) {
      return true;
    } else if (type === 'backspace' && keyCode === 8) {
      return true;
    }
    return false;
  }
}
