// Copyright 1999-2021. Plesk International GmbH. All rights reserved.
const passwordScore = (password, rules = PASSWORD_SCORE_RULES) => {
  const unusedRules = [];
  let score = 0;
  rules.forEach(rule => {
    const mark = rule.score(password);

    if (mark < 0) {
      unusedRules.push({
        rule,
        value: -mark
      });
    } else {
      score += mark;
    }
  });
  return {
    score,
    unusedRules
  };
};

export const PASSWORD_SCORE_RULES = [{
  name: 'passwordTooShort',

  score(passwd) {
    return passwd.length < 5 ? -1 : 0;
  }

}, {
  name: 'passwordLength',

  score(passwd) {
    if (passwd.length < 5) {
      return 3;
    }

    if (passwd.length > 4 && passwd.length < 8) {
      return 6;
    }

    if (passwd.length > 7 && passwd.length < 16) {
      return 12;
    }

    return 18;
  }

}, {
  name: 'lettersLowerCase',

  score(passwd) {
    // [verified] at least one lower case letter
    return passwd.match(/[a-z]/) ? 1 : -1;
  }

}, {
  name: 'lettersUpperCase',

  score(passwd) {
    // [verified] at least one upper case letter
    return passwd.match(/[A-Z]/) ? 5 : -1;
  }

}, {
  name: 'numbers1',

  score(passwd) {
    // [verified] at least one number
    return passwd.match(/\d+/) ? 5 : -1;
  }

}, {
  name: 'numbers3',

  score(passwd) {
    // [verified] at least three numbers
    return passwd.match(/(.*[0-9].*[0-9].*[0-9])/) ? 5 : -1;
  }

}, {
  name: 'specialChar1',

  score(passwd) {
    // [verified] at least one special character
    return passwd.match(/[!@#$%^&*?_~]/) ? 5 : -1;
  }

}, {
  name: 'specialChar2',

  score(passwd) {
    // [verified] at least two special characters
    return passwd.match(/(.*[!@#$%^&*?_~].*[!@#$%^&*?_~])/) ? 5 : -1;
  }

}, {
  name: 'comboUpperAndLower',

  score(passwd) {
    // [verified] both upper and lower case
    return passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ? 2 : -1;
  }

}, {
  name: 'comboLettersAndNumbers',

  score(passwd) {
    // [verified] both letters and numbers
    return passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/) ? 2 : -1;
  }

}, {
  name: 'comboLettersNumbersSpecial',

  score(passwd) {
    // [verified] letters, numbers, and special characters
    return passwd.match(/([a-zA-Z0-9].*[!@#$%^&*?_~])|([!@#$%^&*?_~].*[a-zA-Z0-9])/) ? 2 : -1;
  }

}];
export default passwordScore;