"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataTable = void 0;

var _react = _interopRequireDefault(require("react"));

require("./DataTable.css");

var _ = require("../");

var _Pagination = _interopRequireDefault(require("../../Pagination"));

var R = _interopRequireWildcard(require("ramda"));

var _sortingHelper = require("./sortingHelper");

var _propTypes = _interopRequireDefault(require("prop-types"));

var _LoadingAnimation = _interopRequireDefault(require("../../LoadingAnimation"));

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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; }

var generateHeaders = function generateHeaders(_ref) {
  var columns = _ref.columns,
      tableProps = _objectWithoutProperties(_ref, ["columns"]);

  return columns.map(function (column, index) {
    return generateHeader(column, index, tableProps);
  });
};

var generateHeader = function generateHeader(column, index, tableProps) {
  var sortable = tableProps.sortable,
      sortingOption = tableProps.sortingOption,
      onSort = tableProps.onSort,
      data = tableProps.data;
  var currentLabel = column.label,
      width = column.width;

  var isCurrentColumnSorted = function isCurrentColumnSorted() {
    return sortingOption.label === currentLabel;
  };

  var headerClickHandler = function headerClickHandler() {
    var order = sortingOption.order;
    var currentOrder = isCurrentColumnSorted() ? order : null;
    var nextOrder = (0, _sortingHelper.getNextOrder)(currentOrder);
    var nextData = (0, _sortingHelper.getNextData)(index, currentOrder, data);
    onSort({
      sortingOption: {
        label: currentLabel,
        order: nextOrder
      },
      data: nextData
    });
  };

  return _react.default.createElement(_.Th, {
    id: "label",
    style: width && {
      width: width
    },
    className: "\n        ".concat(sortable && 'vs-data-table-header-sortable', "\n        ").concat(sortable && isCurrentColumnSorted() && 'vs-data-table-header-sorted', "\n      "),
    key: index,
    onClick: sortable ? headerClickHandler : undefined
  }, _react.default.createElement("div", null, currentLabel, _react.default.createElement("span", null, sortable && (0, _sortingHelper.getSortingIcon)(sortingOption, currentLabel))));
};

var generateRows = function generateRows(_ref2) {
  var data = _ref2.data,
      tableProps = _objectWithoutProperties(_ref2, ["data"]);

  return data.map(function (rowData, index) {
    return generateRow(rowData, index, tableProps);
  });
};

var generateRow = function generateRow(rowData, index, tableProps) {
  var _onClick = tableProps.onClick,
      columns = tableProps.columns,
      selectable = tableProps.selectable,
      onSelect = tableProps.onSelect;
  var id = rowData.id,
      row = rowData.row,
      selected = rowData.selected;
  return _react.default.createElement(_.Tr, {
    key: id
  }, selectable && _react.default.createElement(_.Td, null, _react.default.createElement("input", {
    type: "checkbox",
    "aria-label": "Select row from data table",
    checked: selected,
    onChange: function onChange() {
      onSelect(id);
    }
  })), row.map(function (item, columnIndex) {
    var getColumn = R.compose(R.defaultTo({}), R.prop(columnIndex));

    var _getColumn = getColumn(columns),
        label = _getColumn.label,
        clickable = _getColumn.clickable,
        _getColumn$renderCell = _getColumn.renderCell,
        renderCell = _getColumn$renderCell === void 0 ? R.identity : _getColumn$renderCell;

    return _react.default.createElement(_.Td, {
      key: columnIndex
    }, clickable && _react.default.createElement("a", {
      className: "vs-data-table-clickable-cell",
      onClick: function onClick() {
        _onClick({
          value: item,
          rowIndex: index,
          label: label
        });
      }
    }, renderCell(item)), !clickable && renderCell(item));
  }));
};

var getDataWithPagination = function getDataWithPagination(rowsPerPage, page) {
  return R.compose(R.take(rowsPerPage), R.drop(rowsPerPage * (page - 1)));
};

var NoDataLabel = function NoDataLabel(_ref3) {
  var label = _ref3.label;
  return _react.default.createElement("div", {
    className: "vs-data-table-no-data-label"
  }, label);
};

var omitGeneratedIdsFromData = function omitGeneratedIdsFromData(data) {
  return R.map(R.dissoc("id"))(data);
};

var toggleSelectedInRowData = function toggleSelectedInRowData(rowData) {
  return _objectSpread({}, rowData, {
    selected: !rowData.selected
  });
};

var selectAllCheckbox = function selectAllCheckbox(_ref4) {
  var data = _ref4.data,
      onSelect = _ref4.onSelect;
  var checked = R.all(R.propEq('selected', true))(data);

  var onChange = function onChange() {
    return onSelect({
      data: R.map(function (rowData) {
        return _objectSpread({}, rowData, {
          selected: !checked
        });
      })(data)
    });
  };

  return _react.default.createElement("input", {
    type: "checkbox",
    "aria-label": "Select all from data table",
    checked: checked,
    onChange: onChange
  });
};

var DataTable = function DataTable(_ref5) {
  var _ref5$caption = _ref5.caption,
      caption = _ref5$caption === void 0 ? '' : _ref5$caption,
      _ref5$description = _ref5.description,
      description = _ref5$description === void 0 ? '' : _ref5$description,
      _ref5$columns = _ref5.columns,
      columns = _ref5$columns === void 0 ? [] : _ref5$columns,
      _ref5$data = _ref5.data,
      data = _ref5$data === void 0 ? [] : _ref5$data,
      _ref5$isLoading = _ref5.isLoading,
      isLoading = _ref5$isLoading === void 0 ? false : _ref5$isLoading,
      loadingMessage = _ref5.loadingMessage,
      _ref5$rowsPerPage = _ref5.rowsPerPage,
      rowsPerPage = _ref5$rowsPerPage === void 0 ? 25 : _ref5$rowsPerPage,
      _ref5$page = _ref5.page,
      page = _ref5$page === void 0 ? 1 : _ref5$page,
      onPageChange = _ref5.onPageChange,
      _ref5$pagination = _ref5.pagination,
      pagination = _ref5$pagination === void 0 ? false : _ref5$pagination,
      _ref5$sortingOption = _ref5.sortingOption,
      sortingOption = _ref5$sortingOption === void 0 ? {} : _ref5$sortingOption,
      _ref5$sortable = _ref5.sortable,
      sortable = _ref5$sortable === void 0 ? false : _ref5$sortable,
      onClick = _ref5.onClick,
      onSort = _ref5.onSort,
      renderToolbar = _ref5.renderToolbar,
      _ref5$noDataLabel = _ref5.noDataLabel,
      noDataLabel = _ref5$noDataLabel === void 0 ? 'No data available.' : _ref5$noDataLabel,
      rowsPerPageTemplate = _ref5.rowsPerPageTemplate,
      totalRecordsTemplate = _ref5.totalRecordsTemplate,
      _ref5$selectable = _ref5.selectable,
      selectable = _ref5$selectable === void 0 ? false : _ref5$selectable,
      onSelect = _ref5.onSelect,
      restProps = _objectWithoutProperties(_ref5, ["caption", "description", "columns", "data", "isLoading", "loadingMessage", "rowsPerPage", "page", "onPageChange", "pagination", "sortingOption", "sortable", "onClick", "onSort", "renderToolbar", "noDataLabel", "rowsPerPageTemplate", "totalRecordsTemplate", "selectable", "onSelect"]);

  var paginatedData = pagination ? getDataWithPagination(rowsPerPage, page)(data) : data;

  var onSelectId = function onSelectId(id) {
    var selectedRowIndex = R.findIndex(R.propEq('id', id), data);
    var dataWithSelectedRow = R.adjust(selectedRowIndex, toggleSelectedInRowData)(data);
    onSelect({
      data: dataWithSelectedRow
    });
  };

  return _react.default.createElement(_.TableContainer, _extends({}, restProps, {
    className: "vs-data-table-container"
  }), _react.default.createElement(_.TableTitle, null, _react.default.createElement("div", {
    className: "vs-data-table-top-level-header"
  }, _react.default.createElement("div", null, caption, _react.default.createElement("p", null, description)), _react.default.createElement("div", null, renderToolbar && renderToolbar({
    columns: columns,
    data: omitGeneratedIdsFromData(data)
  })))), isLoading ? _react.default.createElement("div", {
    className: 'vs-data-table-loading-animation-wrapper'
  }, _react.default.createElement(_LoadingAnimation.default, {
    loadingMessage: loadingMessage
  })) : _react.default.createElement(_react.default.Fragment, null, _react.default.createElement(_.Table, null, _react.default.createElement(_.THead, null, _react.default.createElement(_.Tr, null, selectable && _react.default.createElement(_.Th, null, selectAllCheckbox({
    data: data,
    onSelect: onSelect
  })), generateHeaders({
    columns: columns,
    sortable: sortable,
    sortingOption: sortingOption,
    onSort: onSort,
    data: data
  }))), _react.default.createElement(_.TBody, null, generateRows({
    data: paginatedData,
    onClick: onClick,
    columns: columns,
    selectable: selectable,
    onSelect: onSelectId
  }))), paginatedData.length === 0 && _react.default.createElement(NoDataLabel, {
    label: noDataLabel
  }), pagination && _react.default.createElement(_Pagination.default, {
    className: "vs-table-pagination",
    numberOfRows: data.length,
    rowsPerPage: rowsPerPage,
    page: page,
    onChange: onPageChange,
    rowsPerPageTemplate: rowsPerPageTemplate,
    totalRecordsTemplate: totalRecordsTemplate
  })));
};

exports.DataTable = DataTable;
DataTable.propTypes = {
  caption: _propTypes.default.string,
  description: _propTypes.default.string,
  columns: _propTypes.default.array,
  data: _propTypes.default.array,
  isLoading: _propTypes.default.bool,
  loadingMessage: _propTypes.default.string,
  rowsPerPage: _propTypes.default.number,
  page: _propTypes.default.number,
  onPageChange: _propTypes.default.func,
  pagination: _propTypes.default.bool,
  sortingOption: _propTypes.default.shape({
    label: _propTypes.default.string,
    order: _propTypes.default.string
  }),
  sortable: _propTypes.default.bool,
  onSort: _propTypes.default.func,
  selectable: _propTypes.default.bool,
  onSelect: _propTypes.default.func,
  onClick: _propTypes.default.func,
  renderToolbar: _propTypes.default.func,
  noDataLabel: _propTypes.default.string,
  rowsPerPageTemplate: _propTypes.default.string,
  totalRecordsTemplate: _propTypes.default.string
};