import React from 'react';

import PasswordStrength from '../../modules/PasswordStrength';

/**
 * Creates a `<PasswordStrength>` component managed via form context
 * Should be called with Context containing (at least) the following:
 *  - the `password` to validate
 *  - a `handlePasswordValidation()` function to receive the validation status
 * @param {string} displayName - Display name for the returned component.
 * @param {Object} Context - Form context.
 * @returns {Object} component
 */
const createPasswordStrengthComponent = (displayName, Context) => {
  const Component = (props) => (
    <Context.Consumer>
      { (state) => {
        /**
         * Handles password validation information
         * Sends these to the form as well as any `onValidate` handler.
         * Ideally this would be a class method, but Enzyme doesn't yet support
         * the `contextType` API so we wouldn't be able to test it.
         * @param {boolean} isValid - Whether the password is valid.
         * @returns {void}
         */
        const handlePasswordValidation = (isValid) => {
          state.handlePasswordValidation(isValid);

          const { onValidate } = props;
          if (onValidate) {
            onValidate(isValid);
          }
        };

        return (
          <PasswordStrength
            { ...props }
            onValidate={ handlePasswordValidation }
            password={ state.password }
          />
        );
      } }
    </Context.Consumer>
  );

  Component.displayName = displayName;
  Component.propTypes = { ...PasswordStrength.propTypes };

  // The `password` prop is set from the form context and cannot be overridden.
  delete Component.propTypes.password;

  return Component;
};

export default createPasswordStrengthComponent;
