interface Params {
  password: string;
  length?: number;
  shouldHaveNumber?: boolean;
  shouldHaveCapital?: boolean;
  shouldHaveNoSpecialChars?: boolean;
  invalidChars?: string;
  shouldHaveSpecialChars?: boolean;
}

interface Result {
  error: boolean;
  message: string;
}

const usePasswordValidator = ({
  password,
  length = 6,
  shouldHaveNumber = true,
  shouldHaveCapital = true,
  shouldHaveNoSpecialChars = true,
  invalidChars = '?!',
  shouldHaveSpecialChars = true,
}: Params) => {
  if (!password) return false;

  let result: Result = {
    error: false,
    message: `Password is valid`,
  };

  // test length
  if (password.length >= length) {
    for (let loop = 0; loop < password.length; loop += 1) {
      // cannot have spaces
      if (password.charCodeAt(loop) === 32) {
        // does not, throw an error
        result = {
          error: true,
          message: `Spaces are not allowed`,
        };
      }
    }
  } else {
    // does not, throw an error
    result = {
      error: true,
      message: `Your password must be at least ${length} characters long`,
    };
  }

  // test if it should have a number
  if (shouldHaveNumber === true && !/\d/.test(password)) {
    // does not, throw an error
    result = {
      error: true,
      message: `Passwords must have a number`,
    };
  }

  //test if there are  any special characters
  if (shouldHaveNoSpecialChars === true) {
    for (let loop = 0; loop < password.length; loop += 1) {
      if (invalidChars.indexOf(password.charAt(loop)) !== -1) {
        // has invalid char, throw error
        result = {
          error: true,
          message: `Password cannot contain ${invalidChars}`,
        };
      }
    }
  }

  // test if it has a capital letter
  if (shouldHaveCapital === true && !/[A-Z]/.test(password)) {
    // does not, throw an error
    result = {
      error: true,
      message: `Password must have a capital letter`,
    };
  }

  //test if it has a special character
  if (shouldHaveSpecialChars === true && !/[ !"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/.test(password)) {
    // does not, throw an error
    result = {
      error: true,
      message: `Password must have a special character`,
    };
  }

  return { ...result };
};

export default usePasswordValidator;
