import { path } from 'ramda';
import React, { Component } from 'react';
import { Checkbox } from 'semantic-ui-react';

import Context from './Context';

/* Interface */
const propTypes = {
  ...Checkbox.propTypes,

  /** HTML name for the element. */
  name: path(['name', 'isRequired'], Checkbox.propTypes),
  // Access with `path` as React SUI defines no `propTypes` in production builds
};

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

/**
 * Checkbox for a RegisterForm
 * Must be ticked before the form can be submitted. Any number of checkboxes may
 * be added to a form.
 * All props are passed down to SUI's `<Checkbox>`
 * @returns {Object} component
 */
export class RegisterFormCheckbox extends Component {
  /**
   * Notify the parent form that the checkbox exists
   * Checkboxes start out unchecked.
   * @returns {void}
   */
  componentDidMount = () => {
    const { name } = this.props;

    // Enzyme doesn't support the `contextType` API so we can't pass the context
    // when shallow-mounting the component during tests.
    // Avoid tests blowing up by checking the function exists before calling it.
    if (this.context.handleCheckboxChange) {
      this.context.handleCheckboxChange(null, { checked: false, name });
    }
  };

  /**
   * Handles changes to the checkbox state
   * Sends these to the form as well as any `onChange` handler.
   * Note that `event.preventDefault()` is not supported.
   * @param {Array<any>} params - Event parameters.
   * @returns {void}
   */
  handleChange = (...params) => {
    this.context.handleCheckboxChange(...params);

    const { onChange } = this.props;
    if (onChange) {
      onChange(...params);
    }
  };

  render = () => {
    const { name } = this.props;
    const checked = path(['checkboxes', name], this.context);

    return (
      <Checkbox
        { ...this.props }
        checked={ checked }
        onChange={ this.handleChange }
      />
    );
  };
}

RegisterFormCheckbox.contextType = Context;
RegisterFormCheckbox.propTypes = propTypes;

export default RegisterFormCheckbox;
