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

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

  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.width();
    ghostElement.remove();
    return width;
  }

  function getFontStyles(input) {
    return {
      'font-size': angular.element(input).css('font-size'),
      'font-family': angular.element(input).css('font-family'),
      'font-weight': angular.element(input).css('font-weight'),
      'font-style': angular.element(input).css('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;
  }
}
