import { i18n } from '@plugins/i18n';
import { CommonRuleFunctionType, StringRuleFunctionType } from './types/main';

export function noEmptyValueRule(
  val?: string | number | File[]
): boolean | string {
  if (typeof val === 'number') {
    return true;
  }
  return (
    (!!val && val.length > 0) || String(i18n.t('validation.basic.required'))
  );
}

export function noEmptyValueWithCustomMessageRule(
  message: string
): CommonRuleFunctionType {
  return (val: string | File[]) => {
    return val?.length > 0 || message;
  };
}

export function noEmptyCustomValueRule(
  customValue: boolean
): CommonRuleFunctionType {
  return () => {
    return Boolean(customValue) || String(i18n.t('validation.basic.required'));
  };
}

export function noEmptyCustomValueWithCustomMessageRule(
  customValue: any,
  message: string
): CommonRuleFunctionType {
  return () => {
    return customValue || message;
  };
}

export function exactNumberOfCharsRule(
  numOfChars: number
): StringRuleFunctionType {
  return (val: string) => {
    return val
      ? val.trim().length === numOfChars ||
          String(
            i18n.t('validation.basic.exactNumOfChars', {
              num: numOfChars,
            })
          )
      : !val;
  };
}

export function maxNumOfChars(numOfChars: number): StringRuleFunctionType {
  return (val: string) => {
    return val
      ? val.trim().length <= numOfChars ||
          String(
            i18n.t('validation.basic.maxNumOfChars', {
              num: numOfChars,
            })
          )
      : !val;
  };
}

export function validPhoneNumberRule(val: string): boolean | string {
  const pattern = /^\+?([78][|\- ]?)(\(\d{3}\)|\d{3})[\s|\- ]?(\d{3}[\s|\- ]?)(\d{2}[\s|\- ]?)(\d{2}[\s|\- ]?)$/;
  return val
    ? pattern.test(val) || String(i18n.t('validation.basic.invalidPhoneNumber'))
    : !val;
}

export function validEmailRule(val: string): boolean | string {
  const pattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,4}[a-zA-Z]{2,63}$/;
  return val
    ? pattern.test(val) || String(i18n.t('validation.basic.invalidEmail'))
    : !val;
}

export function validEmailRuleBoolean(val: string): boolean {
  const pattern = /^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,4}[a-zA-Z]{2,63}$/;
  return pattern.test(val);
}
