export const getDataId = (string: string) =>
  string.toLowerCase().replace(/([.+_])/g, (match: string) => (match === '_' ? '-' : ''));

export const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();

const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
const reHasRegExpChar = RegExp(reRegExpChar.source);
export const escapeRegExp = (string: string) =>
  string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, '\\$&') : string || '';

const urlRegExp = new RegExp(
  '^(https?:\\/\\/)' +
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}' +
    '|((\\d{1,3}\\.){3}\\d{1,3}))' +
    '(:\\d+)?' +
    '(\\/[-a-z\\d%_.~+]*)*' +
    '(\\?[;&a-z\\d%_.~+=\\[\\]-]*)?' +
    '(#\\S*)?$',
  'i',
);

export const isValidUrl = (string: string) => {
  if (!urlRegExp.test(string)) {
    return false;
  }
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
};

export const isValidUrlEmptyAllowed = (string: string) => {
  if (!string) {
    return true;
  }
  return isValidUrl(string);
};

export default {};
