"use strict";

exports.__esModule = true;
exports.default = void 0;
var _isEmpty2 = _interopRequireDefault(require("lodash/fp/isEmpty"));
var _includes2 = _interopRequireDefault(require("lodash/fp/includes"));
var _size2 = _interopRequireDefault(require("lodash/fp/size"));
var _isString2 = _interopRequireDefault(require("lodash/fp/isString"));
var _get2 = _interopRequireDefault(require("lodash/fp/get"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _buttonLinkIcon = _interopRequireDefault(require("../../atom/button-link-icon"));
var _statusItem = _interopRequireDefault(require("../../atom/status-item"));
var _bulkProgressBar = _interopRequireDefault(require("../bulk-progress-bar"));
var _provider = _interopRequireWildcard(require("../../atom/provider"));
var _bulletPointMenuButton = _interopRequireDefault(require("../bullet-point-menu-button"));
var _buttonLink = _interopRequireDefault(require("../../atom/button-link"));
var _errorsTable = _interopRequireDefault(require("../errors-table"));
var _emptySearchResult = _interopRequireDefault(require("../../atom/empty-search-result"));
var _style = _interopRequireDefault(require("./style.css"));
var _types = require("./types");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
const buildField = field => {
  if ((0, _isString2.default)(field)) return field;
  const {
    componentType
  } = field;
  switch (componentType) {
    case 'status':
      return /*#__PURE__*/_react.default.createElement("div", {
        className: _style.default.statusItemWrapper
      }, /*#__PURE__*/_react.default.createElement(_statusItem.default, field));
    case 'progress-bar':
      return /*#__PURE__*/_react.default.createElement(_bulkProgressBar.default, field);
  }
};
const buildLastField = lastField => {
  const {
    componentType
  } = lastField;
  switch (componentType) {
    case 'menu':
      return /*#__PURE__*/_react.default.createElement(_bulletPointMenuButton.default, lastField);
    case 'button-link':
      return /*#__PURE__*/_react.default.createElement(_buttonLink.default, lastField);
  }
};
const buildNestedRow = row => {
  const {
    componentType
  } = row;
  switch (componentType) {
    case 'errors-table':
      return /*#__PURE__*/_react.default.createElement(_errorsTable.default, row);
    case 'expandible-errors-table':
      return /*#__PURE__*/_react.default.createElement(ActionableExpandableTable, row);
  }
};
const ActionableExpandableTable = (props, legacyContext) => {
  const {
    columns,
    rows = [],
    lastField,
    stickyFirstColumn = false,
    stickyLastColumn = false,
    ariaDescribedby,
    columnWidth = `${100 / (0, _size2.default)(columns)}%`,
    isNestedTable = false,
    emptyStateFistMessage = '',
    emptyStateSecondMessage = ''
  } = props;
  const translate = (0, _provider.GetTranslateFromContext)(legacyContext);

  /**
   * State variable to keep track of all the expanded rows
   * By default, nothing expanded. Hence initialized with empty array.
   */
  const [expandedRows, setExpandedRows] = (0, _react.useState)([]);

  /**
   * State variable to keep track which row is currently expanded.
   */
  const [expandState, setExpandState] = (0, _react.useState)({});
  if ((0, _isEmpty2.default)(columns)) return /*#__PURE__*/_react.default.createElement("div", {
    className: _style.default.wrapper
  }, /*#__PURE__*/_react.default.createElement(_emptySearchResult.default, {
    firstMessage: emptyStateFistMessage,
    secondMessage: emptyStateSecondMessage,
    isBulk: true
  }));

  /**
   * This function gets called when show/hide link is clicked.
   */
  const handleExpandRow = index => () => {
    const isRowExpanded = (0, _includes2.default)(index, expandedRows);

    /**
     * If the row is expanded, we are here to hide it. Hence remove
     * it from the state variable. Otherwise add to it.
     */
    const newExpandedRows = isRowExpanded ? expandedRows.filter(id => id !== index) : expandedRows.concat(index);
    setExpandedRows(newExpandedRows);

    /**
     * Create a new object to update the expanded state of all rows
     * Use the newExpandedRows array to set the state of all rows that are currently expanded
     */
    const expandedState = {};
    newExpandedRows.forEach(id => {
      expandedState[id] = true;
    });
    setExpandState(expandedState);
  };
  const headerRow = columns.map((column, cIndex) => {
    const {
      title
    } = column;
    return /*#__PURE__*/_react.default.createElement("th", {
      className: cIndex === 0 ? (0, _classnames.default)(stickyFirstColumn ? _style.default.headerFirstSticky : _style.default.headerFirst, _style.default.header) : _style.default.header,
      key: `${title}-${cIndex}`,
      role: "columnheader"
    }, title);
  });
  headerRow.push(/*#__PURE__*/_react.default.createElement("th", {
    className: stickyLastColumn ? _style.default.headerLastSticky : _style.default.headerLast,
    key: "action-header"
  }));
  const headerView = [...headerRow];
  const bodyView = rows.map((row, index) => {
    const {
      fields,
      isRowExpandible = false
    } = row;
    const bodyRow = fields.map((field, fIndex) => {
      const cellContent = fIndex === 0 ? /*#__PURE__*/_react.default.createElement("div", {
        className: _style.default.columFirstWrapper
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: _style.default.expandButtonWrapper
      }, isRowExpandible ? /*#__PURE__*/_react.default.createElement(_buttonLinkIcon.default, {
        onClick: handleExpandRow(index),
        "data-name": `arrowUp-button-${index}`,
        icon: "down",
        className: expandState[index] ? 'bulkArrowUp' : 'bulkArrowDown',
        "aria-label": translate('bulk_import.show_errors')
      }) : null), buildField(field)) : buildField(field);
      return /*#__PURE__*/_react.default.createElement("td", {
        className: fIndex === 0 ? (0, _classnames.default)(stickyFirstColumn ? _style.default.columnFirstSticky : _style.default.columnFirst, _style.default.col) : _style.default.col,
        style: {
          width: columnWidth
        },
        key: `${field}-${fIndex}`
      }, cellContent);
    });
    bodyRow.push(/*#__PURE__*/_react.default.createElement("td", {
      className: stickyLastColumn ? _style.default.columnLastSticky : _style.default.columnLast,
      key: "actionHeader"
    }, lastField ? /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)({
        [_style.default.inspectButton]: (0, _get2.default)('className', lastField) === 'bulkInspectButton'
      })
    }, buildLastField(lastField)) : null));
    const nestedRow = (0, _get2.default)('nestedRow', row);
    const nestedRowCellule = nestedRow && expandedRows.includes(index) ? /*#__PURE__*/_react.default.createElement("tr", {
      key: `line-${index}-error`
    }, /*#__PURE__*/_react.default.createElement("td", {
      className: _style.default.nestedRowCellule,
      colSpan: fields.length + 2
    }, buildNestedRow(nestedRow))) : null;
    return nestedRowCellule ? [/*#__PURE__*/_react.default.createElement("tr", {
      key: `line-${index}`
    }, bodyRow), nestedRowCellule] : [/*#__PURE__*/_react.default.createElement("tr", {
      key: `line-${index}`
    }, bodyRow)];
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    className: _style.default.wrapper
  }, /*#__PURE__*/_react.default.createElement("table", _extends({}, ariaDescribedby ? {
    'aria-describedby': ariaDescribedby
  } : {}, {
    className: _style.default.table,
    "data-testid": "expandible-actionable-table",
    "data-name": "expandible-actionable-table"
  }), /*#__PURE__*/_react.default.createElement("thead", {
    className: isNestedTable ? _style.default.theadNested : _style.default.thead
  }, /*#__PURE__*/_react.default.createElement("tr", null, headerView)), /*#__PURE__*/_react.default.createElement("tbody", null, bodyView)));
};
ActionableExpandableTable.contextTypes = {
  skin: _provider.default.childContextTypes.skin,
  translate: _provider.default.childContextTypes.translate
};
ActionableExpandableTable.propTypes = process.env.NODE_ENV !== "production" ? _types.propTypes : {};
var _default = exports.default = ActionableExpandableTable;
//# sourceMappingURL=index.js.map