'use strict';

import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { Checkbox } from '../../form/Checkbox';
export var ListControlCheckbox =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(ListControlCheckbox, _React$Component);

  function ListControlCheckbox() {
    return _React$Component.apply(this, arguments) || this;
  }

  var _proto = ListControlCheckbox.prototype;

  _proto.getVisibleItems = function getVisibleItems() {
    return this.context.listStore.getPrimaryKeys();
  };

  _proto.onChange = function onChange() {
    var _this = this;

    var formRecords = this.context.form.value;
    var items = this.getVisibleItems();
    var checked = this.refs.input.getValue();
    var newFormValue = {};
    items.forEach(function (id) {
      var _$extend;

      newFormValue[id] = _.extend({}, formRecords[id], (_$extend = {}, _$extend[_this.props.dependentFieldName] = checked, _$extend));
    });
    this.context.form.setValue(newFormValue);
  };

  _proto.render = function render() {
    var _this2 = this;

    var formRecords = this.context.form.value;
    var items = this.getVisibleItems();
    var checkboxValue = false;

    if (items.length > 0) {
      var selectedItems = items.filter(function (id) {
        return formRecords[id] && formRecords[id][_this2.props.dependentFieldName];
      });

      if (selectedItems.length === items.length) {
        checkboxValue = true;
      }

      if (selectedItems.length > 0 && selectedItems.length < items.length) {
        checkboxValue = null;
      }
    }

    return React.createElement(Checkbox, {
      "aria-checked": checkboxValue === null ? 'mixed' : checkboxValue,
      checked: checkboxValue,
      hiddenLabel: this.props.hiddenLabel,
      disabled: items.length === 0,
      onChange: this.onChange.bind(this),
      ref: "input",
      label: this.props.label,
      groupClassName: "rc-list-checkbox",
      "aria-labelledby": this.props.ariaLabelledById,
      removeName: true
    });
  };

  return ListControlCheckbox;
}(React.Component);

_defineProperty(ListControlCheckbox, "contextTypes", {
  listStore: PropTypes.object,
  form: PropTypes.object
});

_defineProperty(ListControlCheckbox, "propTypes", {
  label: PropTypes.string,
  dependentFieldName: PropTypes.string.isRequired,
  ariaLabelledById: PropTypes.string,
  hiddenLabel: PropTypes.bool
});

_defineProperty(ListControlCheckbox, "defaultProps", {
  label: 'TRANSLATE:SELECT_ALL',
  ariaLabelledById: null,
  hiddenLabel: true
});