"use strict";

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

var _react = require("react");

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

var _core = require("@emotion/core");

var _shortid = _interopRequireDefault(require("shortid"));

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

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 _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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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 _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 _templateObject7() {
  var data = _taggedTemplateLiteral(["\n  border-bottom: 1pt solid lightgray;\n  padding: 0.25rem 1rem;\n  text-align: ", ";\n"]);

  _templateObject7 = function _templateObject7() {
    return data;
  };

  return data;
}

function _templateObject6() {
  var data = _taggedTemplateLiteral([""]);

  _templateObject6 = function _templateObject6() {
    return data;
  };

  return data;
}

function _templateObject5() {
  var data = _taggedTemplateLiteral(["\n  border-bottom: 2pt solid black;\n  border-collapse: separate;\n  cursor: pointer;\n  padding: 0.25rem 1rem;\n  text-align: ", ";\n"]);

  _templateObject5 = function _templateObject5() {
    return data;
  };

  return data;
}

function _templateObject4() {
  var data = _taggedTemplateLiteral(["\n  box-sizing: border-box;\n"]);

  _templateObject4 = function _templateObject4() {
    return data;
  };

  return data;
}

function _templateObject3() {
  var data = _taggedTemplateLiteral(["\n  border-bottom: ", ";\n  border-collapse: separate;\n  padding: 0.25rem 1rem;\n  text-align: center;\n"]);

  _templateObject3 = function _templateObject3() {
    return data;
  };

  return data;
}

function _templateObject2() {
  var data = _taggedTemplateLiteral(["\n  box-sizing: border-box;\n"]);

  _templateObject2 = function _templateObject2() {
    return data;
  };

  return data;
}

function _templateObject() {
  var data = _taggedTemplateLiteral(["\n  width: 100%;\n  height: 100%;\n  margin-bottom: 1rem;\n  background-color: transparent;\n  border-collapse: collapse;\n"]);

  _templateObject = function _templateObject() {
    return data;
  };

  return data;
}

function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

var defaultTableClass = (0, _core.css)(_templateObject());
var defaultHeaderClass = (0, _core.css)(_templateObject2());

var defaultHeaderCellClass = function defaultHeaderCellClass(item) {
  return (0, _core.css)(_templateObject3(), item.underlined ? "1pt solid black" : "");
};

var defaultColumnClass = (0, _core.css)(_templateObject4());

var defaultColumnCellClass = function defaultColumnCellClass(item) {
  return (0, _core.css)(_templateObject5(), item.align || "left");
};

var defaultRowClass = (0, _core.css)(_templateObject6());

var defaultRowCellClass = function defaultRowCellClass(item) {
  return (0, _core.css)(_templateObject7(), item.align || "left");
};

var DefaultColumn = function DefaultColumn(_ref) {
  var columns = _ref.columns,
      sortTable = _ref.sortTable,
      columnClass = _ref.columnClass,
      columnCellClass = _ref.columnCellClass;
  return (0, _core.jsx)("tr", {
    css: columnClass || defaultColumnClass
  }, columns.map(function (item) {
    return (0, _core.jsx)("th", {
      key: _shortid["default"].generate(),
      css: columnCellClass || defaultColumnCellClass(item),
      colSpan: item.colSpan,
      onClick: function onClick() {
        return sortTable(item.key);
      }
    }, item.header);
  }));
};

DefaultColumn.propTypes = {
  columns: _propTypes["default"].arrayOf(_propTypes["default"].shape({
    header: _propTypes["default"].string,
    key: _propTypes["default"].string
  })).isRequired,
  columnClass: _propTypes["default"].string,
  columnCellClass: _propTypes["default"].string,
  sortTable: _propTypes["default"].func.isRequired
};

var DefaultHeader = function DefaultHeader(_ref2) {
  var styles = _ref2.styles,
      columns = _ref2.columns;
  return (0, _core.jsx)("tr", {
    css: styles || defaultHeaderClass
  }, columns.map(function (item) {
    return (0, _core.jsx)("th", {
      key: _shortid["default"].generate(),
      css: defaultHeaderCellClass(item),
      colSpan: item.colSpan || "1"
    }, item.header);
  }));
};

DefaultHeader.propTypes = {
  columns: _propTypes["default"].arrayOf(_propTypes["default"].shape({
    header: _propTypes["default"].string,
    key: _propTypes["default"].string
  })).isRequired,
  styles: _propTypes["default"].string
};

var DefaultRow = function DefaultRow(_ref3) {
  var data = _ref3.data,
      columns = _ref3.columns,
      rowClass = _ref3.rowClass,
      rowCellClass = _ref3.rowCellClass;
  return (0, _core.jsx)("tr", {
    css: rowClass || defaultRowClass
  }, columns.map(function (item) {
    return (0, _core.jsx)("td", {
      key: _shortid["default"].generate(),
      css: rowCellClass || defaultRowCellClass(item)
    }, data[item.key]);
  }));
};

DefaultRow.propTypes = {
  data: _propTypes["default"].shape({}).isRequired,
  columns: _propTypes["default"].arrayOf(_propTypes["default"].shape({
    header: _propTypes["default"].string,
    key: _propTypes["default"].string
  })).isRequired,
  rowClass: _propTypes["default"].string,
  rowCellClass: _propTypes["default"].string
};

var DataTable = function (_Component) {
  _inherits(DataTable, _Component);

  function DataTable(props) {
    var _this;

    _classCallCheck(this, DataTable);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(DataTable).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "compare", function (sortpivot, asc) {
      return function (a, b) {
        var A = a[sortpivot] === null || a[sortpivot] === undefined ? "" : a[sortpivot];
        var B = b[sortpivot] === null || b[sortpivot] === undefined ? "" : b[sortpivot];
        A = typeof a[sortpivot] === "string" ? a[sortpivot].toLowerCase() : a[sortpivot];
        B = typeof b[sortpivot] === "string" ? b[sortpivot].toLowerCase() : b[sortpivot];

        if (asc) {
          if (A > B) return 1;
          if (A < B) return -1;
          return 0;
        }

        if (A > B) return -1;
        if (A < B) return 1;
        return 0;
      };
    });

    _defineProperty(_assertThisInitialized(_this), "flattenColumns", function (topLevelColumns) {
      return Object.values(topLevelColumns).reduce(function (accumulator, currentValue) {
        if (currentValue.columns) {
          accumulator.push.apply(accumulator, _toConsumableArray(currentValue.columns));
        } else {
          accumulator.push(currentValue);
        }

        return accumulator;
      }, []);
    });

    _defineProperty(_assertThisInitialized(_this), "generateHeaderAndColumns", function (topLevelColumns) {
      var _this$props = _this.props,
          HeaderComponent = _this$props.HeaderComponent,
          ColumnComponent = _this$props.ColumnComponent;
      var Header = HeaderComponent || DefaultHeader;
      var Column = ColumnComponent || DefaultColumn;
      var headerValues = [];
      var columnValues = [];
      Object.values(topLevelColumns).forEach(function (item) {
        if (item.columns) {
          headerValues.push(_objectSpread({}, item, {
            colSpan: item.columns.length,
            underlined: true
          }));
          columnValues.push.apply(columnValues, _toConsumableArray(item.columns));
        } else {
          headerValues.push({
            colSpan: "1",
            key: item.key,
            underlined: false
          });
          columnValues.push(_objectSpread({}, item));
        }
      });
      return (0, _core.jsx)("thead", null, (0, _core.jsx)(Header, {
        columns: headerValues
      }), (0, _core.jsx)(Column, {
        columns: columnValues,
        sortTable: _this.sortTable
      }));
    });

    _defineProperty(_assertThisInitialized(_this), "sortTable", function () {
      var sortKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
      var _this$state = _this.state,
          prevSorted = _this$state.sorted,
          asc = _this$state.asc;
      var sorted = Object.values(prevSorted).sort(_this.compare(sortKey, asc));

      _this.setState(function (prevState) {
        return {
          sorted: sorted,
          asc: !prevState.asc
        };
      });
    });

    _this.state = {
      asc: true,
      sorted: props.data.data,
      flattenedColumns: _this.flattenColumns(props.data.columns)
    };
    return _this;
  }

  _createClass(DataTable, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          data = _this$props2.data,
          tableClass = _this$props2.tableClass,
          RowComponent = _this$props2.RowComponent;
      var _this$state2 = this.state,
          sorted = _this$state2.sorted,
          flattenedColumns = _this$state2.flattenedColumns;
      var Row = RowComponent || DefaultRow;
      return (0, _core.jsx)("table", {
        css: tableClass || defaultTableClass
      }, this.generateHeaderAndColumns(data.columns), (0, _core.jsx)("tbody", null, Object.keys(sorted).map(function (id) {
        return (0, _core.jsx)(Row, {
          key: _shortid["default"].generate(),
          id: id,
          columns: flattenedColumns,
          data: sorted[id]
        });
      })));
    }
  }]);

  return DataTable;
}(_react.Component);

exports["default"] = DataTable;
DataTable.propTypes = {
  data: _propTypes["default"].shape({
    columns: _propTypes["default"].arrayOf(_propTypes["default"].shape({
      header: _propTypes["default"].string,
      key: _propTypes["default"].string
    })).isRequired,
    data: _propTypes["default"].arrayOf(_propTypes["default"].shape({})).isRequired
  }).isRequired,
  HeaderComponent: _propTypes["default"].element,
  ColumnComponent: _propTypes["default"].element,
  RowComponent: _propTypes["default"].element,
  tableClass: _propTypes["default"].string
};