import React from "react";
import RadioField from "./radio-field";

export default class CheckboxField extends RadioField {

  static jsClass = 'CheckboxField';

  get type() {
    return 'checkbox';
  }

  onChange(e) {
    const { checked, value, dataset } = e.target;
    const { options } = this.props;
    let { value: setValue } = this.state;
    if (typeof setValue === 'string') {
      try {
        setValue = JSON.parse(setValue.replace(/'/g, '"'));
      } catch (error) {
        console.error("Invalid JSON format: ", error);
        setValue = [];
      }
    }
    if (Array.isArray(options)) {
      setValue = Array.isArray(setValue) ? setValue : [];
      const valueSet = new Set(setValue);
      const typeOfValue = dataset.type === 'number' ? parseFloat(value) : value;
      if (checked) valueSet.add(typeOfValue);
      else valueSet.delete(typeOfValue);
      setValue = Array.from(valueSet);
    } else {
      setValue = checked;
    }
    this.setState({
      value: setValue,
      error: this.isInvalid(setValue)
    }, () => this.returnData());
  }

  get inputProps() {
    const props = super.inputProps;
    props.required = (this.props.required && !this.state.value.length);
    return props;
  }

  content(children = this.props.children) {
    let { options, errorMessage, label, disabled, readOnly } = this.props;
    let { error } = this.state;
    const hasOptions = Array.isArray(options);
    return <>
      {!!label && hasOptions && this.labelNode}
      {hasOptions ?
        options.map(this.nodeOption) :
        // se inserta el valor true para no modificar el algoritmo de nodeOption en el padre
        this.nodeOption({ value: true, label, disabled, readOnly })}
      {children}
      {error && <small className="text-danger">
        {errorMessage}
      </small>}
    </>
  }

}
