import has from 'lodash/has';

/**
 * Utils
 *
 * A collection of helper functions for use in the various
 * payment components. Lifted directly from jquery.payment
 * and reorganized to make things more sane.
 */

 /**
 * Removes all non-numeric characters.
 *
 * @param  {Object} e HTML event
 * @return {string}   Stripped numeric value
 */
export function reformatNumeric(e) {
  const value = e.target.value;
  return value.replace(/\D/g, '');
}

/**
 * Given an HTML event, only allow input for numerics.
 * @param  {Object} e  HTML event
 * @return {Boolean}   Non-numeric input event?
 */
export function restrictNumeric(e) {
  let input;

  // Restrict control key / meta key
  if (e.metaKey || e.ctrlKey) {
    return true;
  }
  // Don't restrict input on space
  if (e.which === 32) {
    return false;
  }
  // Wat
  if (e.which === 0) {
    return true;
  }
  // If it's less than 33, restrict it.
  if (e.which < 33) {
    return true;
  }

  // Test to see if we're dealing with a character or a space
  input = String.fromCharCode(e.which);
  if (!/[\d\s]/.test(input)) {
    e.preventDefault();
    return false;
  }

  return true;
}

/**
 * Given an input, determine if text is selected.
 * @param  {Object}  target [description]
 * @return {Boolean}        [description]
 */
export function hasTextSelected(target) {
  // If some text is selected
  if (target.selectionStart &&
    target.selectionStart !== target.selectionEnd) {
    return true;
  }

  // lmao IE garbage.
  if (has(document, 'selection.createRange')) {
    if (document.selection.createRange().text) {
      return true;
    }
  }
}
