import {urlRegex, arnRegex} from './constants';

export const stripSpace = (str: string): string =>
  str.replace(/\s/, '').toLowerCase();

export const checkNotEmpty = (value: string): string | true =>
  value === '' ? 'Cannot be empty' : true;

export const checkArn = (value: string): string | true => {
  const empty = checkNotEmpty(value);
  if(empty !== true) return empty;
  return arnRegex.test(value) ? true : 'Invalid certificateArn';
};

export const checkName = (existingPublications: { title: string }[]) => (value: string): string | true => {
  const pubCheck = existingPublications.reduce((check: boolean, {title}: {title: string}) => {
    return stripSpace(title) === stripSpace(value)
  }, false);
  if(pubCheck) return 'This publication already exists, please check before proceeding';

  return checkNotEmpty(value);
}

export const checkDomain = (value: string): string | true => {
  const empty = checkNotEmpty(value);
  if(empty !== true) return empty;
  if(value.includes('http://') || value.includes("www.")) return 'should not include http or www';
  return urlRegex.test(value) ? true : 'Invalid domain';
}



