/**
 * Contains user management methods for the User Interface.
 */
class Users {
  /**
   * Creates an instance of the Users class.
   * @param {string} signInForm - The name of the sign-in form calling these methods.
   */
  constructor(signInForm) {
    this.name = 'login';
    this.signInForm = signInForm;
  }

  /**
   * Toggles the login popup.
   */
  toggleLogin() {
    document.getElementById('login_popup').classList.toggle('logon_active');
  }

  /**
   * Executes the logout operation.
   */
  logout() {
    window.location.href = '/signout';
  }

  /**
   * Validates the input fields of a standard login form.
   * @param {Object} elements - The input elements of the form.
   */
  validateInput(elements) {
    /* Validate a standard login form */
    const isValid = this.checkRequiredFields(elements) && this.checkPasswordStrength(elements.password);

    if (isValid) {
      document.forms[this.signInForm].submit();
    }
  }

  /**
   * Checks if the required fields of the form are filled.
   * @param {Object} elements - The input elements of the form.
   * @returns {boolean} - True if all required fields are filled, false otherwise.
   */
  checkRequiredFields(elements) {
    const keys = Object.keys(elements);

    for (let i = 0; i < keys.length; i++) {
      const el = elements[keys[i]];
      if (el.value.length < 1) {
        alert(`Must enter ${el.name}`);
        return false;
      }
    }

    return true;
  }

  /**
   * Checks the strength of the password.
   * @param {Object} passwordElement - The password input element.
   * @returns {boolean} - True if the password meets the strength requirements, false otherwise.
   */
  checkPasswordStrength(passwordElement) {
    const password = passwordElement.value;

    if (password.length < 6) {
      alert('Password must be at least 6 characters.');
      return false;
    }

    if (!/\d/.test(password)) {
      alert('Password must contain at least 1 number.');
      return false;
    }

    if (!/[A-Z]/.test(password)) {
      alert('Password must contain at least 1 uppercase letter.');
      return false;
    }

    if (!/[a-z]/.test(password)) {
      alert('Password must contain at least 1 lowercase letter.');
      return false;
    }

    return true;
  }
}

