function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { KuiListingTableToolBar } from './listing_table_tool_bar';
import { KuiListingTableToolBarFooter } from './listing_table_tool_bar_footer';
import { KuiListingTableRow } from './listing_table_row';
import { KuiControlledTable, KuiTableHeaderCheckBoxCell, KuiTableBody, KuiTableHeader, KuiTable, KuiTableHeaderCell } from '../../index';
import { LEFT_ALIGNMENT, RIGHT_ALIGNMENT } from '../../../services';
export function KuiListingTable(_ref) {
  var rows = _ref.rows,
      header = _ref.header,
      pager = _ref.pager,
      toolBarActions = _ref.toolBarActions,
      onFilter = _ref.onFilter,
      onItemSelectionChanged = _ref.onItemSelectionChanged,
      enableSelection = _ref.enableSelection,
      selectedRowIds = _ref.selectedRowIds,
      filter = _ref.filter,
      prompt = _ref.prompt;

  function areAllRowsSelected() {
    return rows.length > 0 && rows.length === selectedRowIds.length;
  }

  function toggleAll() {
    if (areAllRowsSelected()) {
      onItemSelectionChanged([]);
    } else {
      onItemSelectionChanged(rows.map(function (row) {
        return row.id;
      }));
    }
  }

  function toggleRow(rowId) {
    var selectedRowIndex = selectedRowIds.indexOf(rowId);

    if (selectedRowIndex >= 0) {
      onItemSelectionChanged(selectedRowIds.filter(function (item, index) {
        return index !== selectedRowIndex;
      }));
    } else {
      onItemSelectionChanged([].concat(_toConsumableArray(selectedRowIds), [rowId]));
    }
  }

  function renderTableRows(enableSelection) {
    return rows.map(function (row, rowIndex) {
      return /*#__PURE__*/React.createElement(KuiListingTableRow, {
        key: rowIndex,
        enableSelection: enableSelection,
        isSelected: selectedRowIds.indexOf(row.id) >= 0,
        onSelectionChanged: toggleRow,
        row: row
      });
    });
  }

  function renderHeader() {
    return header.map(function (cell, index) {
      var content = cell.content,
          props = _objectWithoutProperties(cell, ["content"]);

      if ( /*#__PURE__*/React.isValidElement(cell) || !_.isObject(cell)) {
        props = [];
        content = cell;
      }

      return /*#__PURE__*/React.createElement(KuiTableHeaderCell, _extends({
        key: index
      }, props), content);
    });
  }

  function renderInnerTable() {
    return /*#__PURE__*/React.createElement(KuiTable, null, /*#__PURE__*/React.createElement(KuiTableHeader, null, enableSelection && /*#__PURE__*/React.createElement(KuiTableHeaderCheckBoxCell, {
      isChecked: areAllRowsSelected(),
      onChange: toggleAll
    }), renderHeader()), /*#__PURE__*/React.createElement(KuiTableBody, null, renderTableRows(enableSelection)));
  }

  return /*#__PURE__*/React.createElement(KuiControlledTable, null, /*#__PURE__*/React.createElement(KuiListingTableToolBar, {
    actions: toolBarActions,
    pager: pager,
    onFilter: onFilter,
    filter: filter
  }), prompt ? prompt : renderInnerTable(), /*#__PURE__*/React.createElement(KuiListingTableToolBarFooter, {
    itemsSelectedCount: selectedRowIds.length,
    pager: pager
  }));
}
KuiListingTable.propTypes = {
  header: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.node, PropTypes.shape({
    content: PropTypes.node,
    align: PropTypes.oneOf([LEFT_ALIGNMENT, RIGHT_ALIGNMENT]),
    onSort: PropTypes.func,
    isSortAscending: PropTypes.bool,
    isSorted: PropTypes.bool
  })])),
  rows: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string,
    cells: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.node, PropTypes.shape({
      content: PropTypes.node,
      align: PropTypes.oneOf([LEFT_ALIGNMENT, RIGHT_ALIGNMENT])
    })]))
  })),
  pager: PropTypes.node,
  onItemSelectionChanged: PropTypes.func.isRequired,
  enableSelection: PropTypes.bool,
  selectedRowIds: PropTypes.array,
  prompt: PropTypes.node,
  // If given, will be shown instead of a table with rows.
  onFilter: PropTypes.func,
  toolBarActions: PropTypes.node,
  filter: PropTypes.string
};
KuiListingTable.defaultProps = {
  rows: [],
  selectedRowIds: [],
  enableSelection: true
};
