"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useCheckboxCellsState;
var _react = require("react");
/**
 * @typedef {Object} CheckboxesManagement
 * @property {boolean[]} items - checkboxes array state
 * @property {boolean} areAllChecked - property is true when all the checkboxes are checked
 * @property {boolean} areAllUnChecked - property is true when all the checkboxes are unchecked
 * @property {boolean} areSomeChecked - property is true when some the checkboxes are checked, except cases of all or no one
 * @property {function} setCheckboxItems - set new values to the checkboxes
 * @property {function} setAllChecked - set all the checkboxes to checked state
 * @property {function} setAllUnchecked - set all the checkboxes to unchecked state
 * @property {function} setValueByIndex - set checkbox by index into the specific value
 * @property {function} toggleValueByIndex - set checkbox by index into the opposite value
 */

/**
 * Provides state and actions for checkboxes management
 * Example:
 ```
  const {
    items,
    areAllChecked,
    areAllUnChecked,
    areSomeChecked,
    setCheckboxItems,
    setAllChecked,
    setAllUnChecked,
    setValueByIndex,
    toggleValueByIndex
  } = useCheckboxCellsState();

  return (
    <TableWithCheckbox
      checkboxesState={items}
      onSelectAllCheckboxes={setAllChecked}
      setCheckboxByIndex={setValueByIndex}
      toggleCheckboxByIndex={toggleValueByIndex}
    />
  );
 ```
* @param {boolean[]} initialItems
* @returns {CheckboxManagement}
 */
function useCheckboxCellsState(initialItems = []) {
  const [items, setCheckboxItems] = (0, _react.useState)(initialItems);
  return (0, _react.useMemo)(() => {
    const areAllChecked = items.every(item => item);
    const areAllUnChecked = items.every(item => !item);
    const areSomeChecked = !areAllChecked && items.some(item => item);
    return {
      items,
      areAllChecked,
      areAllUnChecked,
      areSomeChecked,
      setCheckboxItems,
      setAllChecked: () => {
        setCheckboxItems(items.map(() => true));
      },
      setAllUnChecked: () => {
        setCheckboxItems(items.map(() => false));
      },
      setValueByIndex: (value, index) => {
        const updatedValues = items.map((item, idx) => idx === index ? value : item);
        setCheckboxItems(updatedValues);
      },
      toggleValueByIndex: index => {
        const updatedValues = items.map((item, idx) => idx === index ? !item : item);
        setCheckboxItems(updatedValues);
      }
    };
  }, [items]);
}