import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectSpread from "@babel/runtime/helpers/objectSpread";

/**
 * Web ToggleButtonGroup Component
 *
 */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { isTrue, extendPropsWithContext, registerElement, validateDOMAttributes, dispatchCustomElementEvent } from '../../shared/component-helper';
import FormRow from '../form-row/FormRow';
import FormStatus from '../form-status/FormStatus';
import Context from '../../shared/Context';
import ToggleButtonGroupContext from './ToggleButtonGroupContext';
const renderProps = {
  on_change: null
};
export const propTypes = {
  label: PropTypes.string,
  title: PropTypes.string,
  multiselect: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  variant: PropTypes.oneOf(['default', 'checkbox', 'radio']),
  left_component: PropTypes.node,
  disabled: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  id: PropTypes.string,
  name: PropTypes.string,
  status: PropTypes.string,
  status_state: PropTypes.string,
  status_animation: PropTypes.string,
  layout_direction: PropTypes.oneOf(['column', 'row']),
  direction: PropTypes.oneOf(['horizontal', 'vertical']),
  vertical: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  value: PropTypes.string,
  values: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  attributes: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  class: PropTypes.string,
  /// React props
  className: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.node]),
  // Web Component props
  custom_element: PropTypes.object,
  custom_method: PropTypes.func,
  on_change: PropTypes.func
};
export const defaultProps = _objectSpread({
  label: null,
  title: null,
  multiselect: null,
  variant: null,
  left_component: null,
  disabled: null,
  id: null,
  name: null,
  status: null,
  status_state: 'error',
  status_animation: null,
  direction: 'horizontal',
  vertical: null,
  layout_direction: 'row',
  value: null,
  values: null,
  attributes: null,
  class: null,
  // React props
  className: null,
  children: null,
  // Web Component props
  custom_element: null,
  custom_method: null
}, renderProps);
export default class ToggleButtonGroup extends PureComponent {
  static enableWebComponent() {
    registerElement(ToggleButtonGroup.tagName, ToggleButtonGroup, defaultProps);
  }

  static getDerivedStateFromProps(props, state) {
    if (state._listenForPropChanges) {
      if (props.value && typeof props.value !== 'undefined') {
        state.value = props.value;
      }

      if (props.values && typeof props.values !== 'undefined') {
        state.values = ToggleButtonGroup.getValues(props);
      }
    }

    state._listenForPropChanges = true;
    return state;
  }

  static getValues(props) {
    if (typeof props.values === 'string' && props.values[0] === '[') {
      return JSON.parse(props.values);
    }

    return props.values;
  }

  constructor(props) {
    super(props);

    _defineProperty(this, "onChangeHandler", (_ref) => {
      let {
        value,
        event
      } = _ref;
      const {
        multiselect
      } = this.props;
      const {
        values
      } = this.state;

      if (isTrue(multiselect)) {
        if (!values.includes(value)) {
          values.push(value);
        } else {
          values.splice(values.indexOf(value), 1);
        }
      } else {
        this.setState({
          value,
          values,
          _listenForPropChanges: false
        });
      }

      dispatchCustomElementEvent(this, 'on_change', {
        value,
        values,
        event
      });
    });

    this._refInput = React.createRef();
    this._id = props.id || "dnb-toggle-button-group-".concat(Math.round(Math.random() * 999)); // cause we need an id anyway

    this._name = props.name || "dnb-toggle-button-group-".concat(Math.round(Math.random() * 999)); // cause we need an id anyway

    this.state = {
      _listenForPropChanges: true
    };
  }

  render() {
    // consume the formRow context
    const props = this.context.formRow ? // use only the props from context, who are available here anyway
    extendPropsWithContext(this.props, this.context.formRow) : this.props;

    const {
      status,
      status_state,
      status_animation,
      direction,
      vertical,
      layout_direction,
      label,
      variant,
      left_component,
      disabled,
      className,
      class: _className,
      multiselect,
      id: _id,
      // eslint-disable-line
      name: _name,
      // eslint-disable-line
      value: _value,
      // eslint-disable-line
      values: _values,
      // eslint-disable-line
      attributes,
      // eslint-disable-line
      children,
      // eslint-disable-line
      on_change,
      // eslint-disable-line
      custom_method,
      // eslint-disable-line
      custom_element
    } = props,
          rest = _objectWithoutProperties(props, ["status", "status_state", "status_animation", "direction", "vertical", "layout_direction", "label", "variant", "left_component", "disabled", "className", "class", "multiselect", "id", "name", "value", "values", "attributes", "children", "on_change", "custom_method", "custom_element"]);

    const {
      value,
      values
    } = this.state;
    const id = this._id;
    const showStatus = status && status !== 'error';
    const classes = classnames('dnb-toggle-button-group', status && "dnb-toggle-button-group__status--".concat(status_state), "dnb-toggle-button-group--".concat(layout_direction), className, _className);

    const params = _objectSpread({}, rest);

    if (showStatus) {
      params['aria-describedby'] = id + '-status';
    }

    if (label) {
      params['aria-labelledby'] = id + '-label';
    } // also used for code markup simulation


    validateDOMAttributes(this.props, params);
    const context = {
      name: this._name,
      value,
      values,
      multiselect: isTrue(multiselect),
      variant,
      left_component,
      disabled,
      setContext: context => {
        // also look for a fuctions, we we are able to fill old values
        // this is ued in the "constructor" inside the ToggleButton.js component
        if (typeof context === 'function') {
          context = context(this._tmp);
        }

        this._tmp = _objectSpread({}, this._tmp, context);
        this.setState(_objectSpread({}, context, {
          _listenForPropChanges: false
        }));
      },
      onChange: this.onChangeHandler
    };
    const formRowParams = {
      label,
      label_id: id,
      // send the id along, so the FormRow component can use it
      direction,
      vertical,
      disabled // status,
      // status_state

    };
    return React.createElement(ToggleButtonGroupContext.Provider, {
      value: context
    }, React.createElement("span", {
      className: classes
    }, React.createElement(FormRow, formRowParams, React.createElement("span", _extends({
      id: id,
      className: "dnb-toggle-button-group__shell",
      role: "group"
    }, params), children, showStatus && React.createElement(FormStatus, {
      text: status,
      status: status_state,
      text_id: id + '-status' // used for "aria-describedby"
      ,
      animation: status_animation
    })))));
  }

}

_defineProperty(ToggleButtonGroup, "tagName", 'dnb-toggle-button-group');

_defineProperty(ToggleButtonGroup, "defaultProps", defaultProps);

_defineProperty(ToggleButtonGroup, "renderProps", renderProps);

_defineProperty(ToggleButtonGroup, "contextType", Context);

_defineProperty(ToggleButtonGroup, "parseChecked", state => /true|on/.test(String(state)));

ToggleButtonGroup.propTypes = process.env.NODE_ENV !== "production" ? propTypes : {};