"use strict";

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

var React = _interopRequireWildcard(require("react"));

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

var _get = _interopRequireDefault(require("lodash/get"));

var _classnames = _interopRequireDefault(require("classnames"));

var _Table = _interopRequireDefault(require("@material-ui/core/Table"));

var _TableBody = _interopRequireDefault(require("@material-ui/core/TableBody"));

var _TableCell = _interopRequireDefault(require("@material-ui/core/TableCell"));

var _TableHead = _interopRequireDefault(require("@material-ui/core/TableHead"));

var _TableRow = _interopRequireDefault(require("@material-ui/core/TableRow"));

var _withStyles = _interopRequireDefault(require("../../hoc/withStyles"));

var _TriangleArrow = _interopRequireDefault(require("../TriangleArrow"));

var _ErrorBoundary = _interopRequireDefault(require("../../hoc/ErrorBoundary"));

var _Loading = _interopRequireDefault(require("../Loading"));

var _ScrollObserver = _interopRequireDefault(require("../../hoc/ScrollObserver"));

var _styles = _interopRequireDefault(require("./styles"));

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

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 _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 _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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

var Table =
/*#__PURE__*/
function (_React$PureComponent) {
  _inherits(Table, _React$PureComponent);

  function Table() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Table);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Table)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onRequestSort", function (column) {
      return function (event) {
        var sortable = _this.props.sortable;

        if (!sortable || column.notSortable) {
          return;
        }

        if (_this.props.onRequestSort) {
          _this.props.onRequestSort(column);
        }
      };
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onRemoveClicked", function (row) {
      return function (event) {
        if (_this.props.onRemoveClicked) {
          _this.props.onRemoveClicked(row, event);
        }
      };
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onAddClicked", function (row) {
      return function (event) {
        if (_this.props.onAddClicked) {
          _this.props.onAddClicked(row, event);
        }
      };
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onRowClick", function (row) {
      return function (event) {
        var onRowClick = _this.props.onRowClick;

        if (onRowClick) {
          onRowClick(event, row);
        }
      };
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onCellClick", function (_ref) {
      var row = _ref.row,
          column = _ref.column,
          index = _ref.index;
      return function (e) {
        var onCellClick = _this.props.onCellClick;

        if (onCellClick) {
          onCellClick(e, {
            row: row,
            column: column,
            index: index
          });
        }
      };
    });

    return _this;
  }

  _createClass(Table, [{
    key: "_renderSortIcon",
    value: function _renderSortIcon(column) {
      var classes = this.props.classes;

      if (!column.sorted) {
        return React.createElement("div", {
          className: classes.sortIconWrapper
        }, React.createElement(_TriangleArrow.default, {
          color: '#B7B7B7',
          direction: 'up',
          size: 5
        }), React.createElement(_TriangleArrow.default, {
          color: '#B7B7B7',
          classes: {
            component: classes.downArrow
          },
          direction: 'down',
          size: 5
        }));
      }

      return React.createElement("div", {
        className: classes.sortIconWrapper
      }, column.sorted && column.order === 'asc' && React.createElement(_TriangleArrow.default, {
        color: '#B7B7B7',
        direction: 'up',
        size: 5
      }), column.sorted && column.order === 'desc' && React.createElement(_TriangleArrow.default, {
        color: '#B7B7B7',
        direction: 'down',
        size: 5
      }));
    }
  }, {
    key: "_renderHeader",
    value: function _renderHeader() {
      var _this2 = this;

      var _this$props = this.props,
          columnData = _this$props.columnData,
          classes = _this$props.classes,
          sortable = _this$props.sortable,
          showRemoveIcon = _this$props.showRemoveIcon,
          showAddIcon = _this$props.showAddIcon;
      return React.createElement(_TableHead.default, null, React.createElement(_TableRow.default, null, columnData.map(function (column, index) {
        return React.createElement(_TableCell.default, {
          key: index,
          className: (0, _classnames.default)(classes.tableHeaderCellWrapper, (0, _get.default)(column, 'classes.tableHeaderCellWrapper', ''))
        }, React.createElement("div", {
          className: classes.tableHeaderCell,
          onClick: _this2._onRequestSort(column)
        }, React.createElement("div", {
          className: (0, _classnames.default)(classes.tableHeaderText, {
            'sorted-column': column.sorted && sortable
          })
        }, column.label), sortable && !column.notSortable && _this2._renderSortIcon(column)));
      }), showAddIcon && React.createElement(_TableCell.default, {
        padding: "checkbox"
      }), showRemoveIcon && React.createElement(_TableCell.default, {
        padding: "checkbox"
      })));
    }
  }, {
    key: "_renderData",
    value: function _renderData() {
      var _this3 = this;

      var _this$props2 = this.props,
          columnData = _this$props2.columnData,
          data = _this$props2.data,
          classes = _this$props2.classes,
          showRemoveIcon = _this$props2.showRemoveIcon,
          showAddIcon = _this$props2.showAddIcon,
          cellStyler = _this$props2.cellStyler,
          loading = _this$props2.loading;
      var totalColumns = columnData.length;

      if (showAddIcon) {
        totalColumns++;
      }

      if (showRemoveIcon) {
        totalColumns++;
      }

      return React.createElement(_TableBody.default, null, data.map(function (row, index) {
        return React.createElement(_TableRow.default, {
          "data-test": "row-".concat(index),
          classes: {
            root: classes.tableRowRoot
          },
          key: index,
          onClick: _this3._onRowClick(row)
        }, columnData.map(function (column, index) {
          var columnClasses = column.classes || {};
          var cellText = row[column.id] !== '' && typeof row[column.id] !== 'undefined' ? row[column.id] : column.default || '—';
          var cellTextDom = React.createElement("span", {
            className: (0, _classnames.default)(classes.cellValueText, columnClasses.cellValueText)
          }, cellText);
          return React.createElement(_TableCell.default, {
            "data-test": "cell-".concat(cellText, "-").concat(index),
            className: (0, _classnames.default)(classes.tableCellRoot, columnClasses.tableCellRoot),
            onClick: _this3._onCellClick({
              row: row,
              column: column,
              index: index
            }),
            key: index
          }, React.createElement("div", {
            className: (0, _classnames.default)(classes.cellValue, columnClasses.cellValue, cellStyler ? cellStyler(row, column) : '')
          }, _this3.props.cellRenderer ? _this3.props.cellRenderer(row, column, cellTextDom) : cellTextDom));
        }), showAddIcon && React.createElement(_TableCell.default, {
          className: (0, _classnames.default)(classes.tableCellRoot, classes.closeIconCellRoot),
          padding: "checkbox",
          onClick: _this3._onAddClicked(row)
        }, React.createElement("div", {
          className: classes.closeIcon
        }, React.createElement("i", {
          className: (0, _classnames.default)('ion-plus')
        }))), showRemoveIcon && React.createElement(_TableCell.default, {
          className: (0, _classnames.default)(classes.tableCellRoot, classes.closeIconCellRoot),
          padding: "checkbox",
          onClick: _this3._onRemoveClicked(row)
        }, React.createElement("div", {
          className: classes.closeIcon
        }, React.createElement("i", {
          className: (0, _classnames.default)('icon icon-close')
        }))));
      }), data.length === 0 && !loading && React.createElement(_TableRow.default, {
        classes: {
          root: classes.tableRowRoot
        }
      }, React.createElement(_TableCell.default, {
        className: classes.tableCellRoot,
        padding: "none",
        colSpan: totalColumns
      }, React.createElement("div", {
        className: classes.noDatCell
      }, "No data to display"))), React.createElement(_TableRow.default, {
        classes: {
          root: (0, _classnames.default)(classes.tableRowRoot, !loading ? classes.hideLoading : '')
        }
      }, React.createElement(_TableCell.default, {
        className: classes.tableCellRoot,
        padding: "none",
        colSpan: totalColumns
      }, React.createElement("div", {
        className: classes.loadingCell
      }, React.createElement(_Loading.default, {
        size: 30
      })))));
    }
  }, {
    key: "_renderTable",
    value: function _renderTable() {
      var classes = this.props.classes;
      return React.createElement(_Table.default, {
        className: (0, _classnames.default)(classes.tableRoot)
      }, this._renderHeader(), this._renderData());
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          classes = _this$props3.classes,
          onBottomReached = _this$props3.onBottomReached,
          onTopReached = _this$props3.onTopReached,
          onBottomReachedThreshold = _this$props3.onBottomReachedThreshold,
          onTopReachedThreshold = _this$props3.onTopReachedThreshold;
      return React.createElement(_ErrorBoundary.default, null, React.createElement(_ScrollObserver.default, {
        onBottomReachedThreshold: onBottomReachedThreshold,
        onBottomReached: onBottomReached,
        onTopReachedThreshold: onTopReachedThreshold,
        onTopReached: onTopReached
      }, React.createElement("div", {
        className: classes.component
      }, this._renderTable())));
    }
  }]);

  return Table;
}(React.PureComponent);

_defineProperty(Table, "propTypes", _objectSpread({
  columnData: _propTypes.default.arrayOf(_propTypes.default.shape({
    id: _propTypes.default.string.isRequired,
    label: _propTypes.default.string.isRequired,
    sorted: _propTypes.default.bool,
    order: _propTypes.default.oneOf(['asc', 'desc']),
    type: _propTypes.default.oneOf(['string', 'date', 'number']),
    classes: _propTypes.default.object
  })).isRequired,
  data: _propTypes.default.array.isRequired,
  onRowClick: _propTypes.default.func,
  onCellClick: _propTypes.default.func,
  sortable: _propTypes.default.bool,
  stripe: _propTypes.default.bool,
  onRequestSort: _propTypes.default.func,
  showRemoveIcon: _propTypes.default.bool,
  onRemoveClicked: _propTypes.default.func,
  showAddIcon: _propTypes.default.bool,
  onAddClicked: _propTypes.default.func,
  cellStyler: _propTypes.default.func,
  cellRenderer: _propTypes.default.func,
  loading: _propTypes.default.bool
}, _ScrollObserver.default.propTypes, {
  classes: _propTypes.default.object
}));

_defineProperty(Table, "defaultProps", {
  stripe: true,
  sortable: true,
  columnData: [],
  data: [],
  onRowClick: function onRowClick() {},
  onCellClick: function onCellClick() {},
  onRequestSort: function onRequestSort() {},
  onRemoveClicked: function onRemoveClicked() {},
  showRemoveIcon: true,
  showAddIcon: false,
  onAddClicked: function onAddClicked() {},
  cellStyler: function cellStyler() {
    return '';
  },
  loading: false,
  onBottomReachedThreshold: 200,
  onTopReachedThreshold: 200
});

var _default = (0, _withStyles.default)(_styles.default)(Table);

exports.default = _default;