"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _isNil2 = _interopRequireDefault(require("ramda/src/isNil"));
var _prop2 = _interopRequireDefault(require("ramda/src/prop"));
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _utils = require("../../../common/utils");
var _ = require("../../..");
var _constants = require("../shared/constants");
var _ColumnProvider = require("../shared/ColumnProvider");
var _HeaderContent = require("./HeaderContent");
var _shared = require("../shared");
var _FlexTableProvider = require("../shared/FlexTableProvider");
var _textUtils = require("../shared/textUtils");
var _FlexTableProvider2 = require("../shared/FlexTableProvider/FlexTableProvider");
var _persistedSortOrder = require("../shared/persistedSortOrder");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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 && Object.prototype.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(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var SORT_ORDERS = [_constants.SORT_ORDER_NONE, _constants.SORT_ORDER_ASCENDING, _constants.SORT_ORDER_DESCENDING];
var getNextSortOrder = function getNextSortOrder(currentOrder) {
  var currentIndex = SORT_ORDERS.indexOf(currentOrder);
  var nextIndex = (currentIndex + 1) % SORT_ORDERS.length;
  return SORT_ORDERS[nextIndex];
};
var getSortOrder = function getSortOrder(stateSortOrder, sortOrderProp, persistedSortOrder, initialSortOrder) {
  return stateSortOrder || sortOrderProp || persistedSortOrder || initialSortOrder;
};
var getDensityStyles = function getDensityStyles(_ref) {
  var density = _ref.density;
  return "\n  padding-top: ".concat((0, _textUtils.getDensityPaddings)(density), "px !important;\n  padding-bottom: ").concat((0, _textUtils.getDensityPaddings)(density), "px;\n");
};
var StyledFlexbox = (0, _styledComponents.default)(_.Flexbox).withConfig({
  displayName: "Header__StyledFlexbox",
  componentId: "sc-5wp0tw-0"
})(["overflow:hidden;", ""], (0, _shared.getStylesForSizes)(function (p) {
  return {
    xs: p.$xs,
    sm: p.$sm,
    md: p.$md,
    lg: p.$lg,
    xl: p.$xl
  };
}, {
  density: getDensityStyles
}));
var Header = function Header(props) {
  var children = props.children,
    className = props.className,
    _props$initialSortOrd = props.initialSortOrder,
    initialSortOrder = _props$initialSortOrd === void 0 ? _constants.SORT_ORDER_NONE : _props$initialSortOrd,
    _props$sortable = props.sortable,
    sortable = _props$sortable === void 0 ? false : _props$sortable,
    sortOrderProp = props.sortOrder,
    _props$onSort = props.onSort,
    onSort = _props$onSort === void 0 ? function () {} : _props$onSort,
    columnId = props.columnId;
  var _useFlexTable = (0, _FlexTableProvider.useFlexTable)('density'),
    xs = _useFlexTable.xs,
    sm = _useFlexTable.sm,
    md = _useFlexTable.md,
    lg = _useFlexTable.lg,
    xl = _useFlexTable.xl;
  var contextData = (0, _react.useContext)(_FlexTableProvider2.FlexTableContext);
  if (contextData === undefined) {
    throw Error('No FlexTable provider, FlexTable rows can only be children of a FlexTable');
  }
  var tableId = contextData.id,
    persistSortingOrder = contextData.persistSortingOrder;
  var _useColumnData = (0, _ColumnProvider.useColumnData)(columnId),
    _useColumnData2 = _slicedToArray(_useColumnData, 2),
    columnState = _useColumnData2[0],
    columnDispatch = _useColumnData2[1];
  var storedSortOrder = persistSortingOrder ? (0, _shared.getPersistedSortOrder)(tableId) : null;
  var persistedSortOrder = storedSortOrder && storedSortOrder.columnId === columnId ? storedSortOrder.sortOrder : null;
  var savedSortOrderExists = persistSortingOrder && (0, _shared.tableHasSavedPersistedSortOrder)(tableId);
  var sortOrder = sortable ? getSortOrder((0, _prop2.default)('sortOrder', columnState), sortOrderProp, persistedSortOrder, savedSortOrderExists ? initialSortOrder : _constants.SORT_ORDER_NONE) : null;
  var ariaSorted = sortable ? {
    'aria-sort': sortOrder
  } : {};
  var cellFlexProps = (0, _ColumnProvider.useFlexCellProps)(props);
  var controlledSort = sortOrderProp !== undefined;
  (0, _react.useEffect)(function () {
    columnDispatch({
      type: _ColumnProvider.ACTION_SET_INITIAL_SORTING,
      sortOrder: sortOrder,
      controlledSort: controlledSort
    });
  }, []);
  (0, _react.useEffect)(function () {
    if (controlledSort) {
      columnDispatch({
        type: _ColumnProvider.ACTION_SET_SORTING,
        sortOrder: sortOrderProp
      });
    }
  }, [sortOrderProp, controlledSort, columnDispatch]);
  var onSortClick = function onSortClick() {
    var newSortOrder = getNextSortOrder(sortOrder || initialSortOrder);
    onSort(columnId, newSortOrder);
    if (!controlledSort) {
      columnDispatch({
        type: _ColumnProvider.ACTION_SET_SORTING,
        sortOrder: newSortOrder
      });
      (0, _persistedSortOrder.setPersistedSortOrder)(tableId, columnId, newSortOrder);
    }
  };
  var sorted = !(0, _isNil2.default)(sortOrder) && sortOrder !== _constants.SORT_ORDER_NONE;
  return _react.default.createElement(StyledFlexbox, _extends({
    className: className,
    role: "columnheader",
    $xs: xs,
    $sm: sm,
    $md: md,
    $lg: lg,
    $xl: xl
  }, ariaSorted, cellFlexProps), (0, _utils.isElement)(children) && children, (0, _utils.isFunction)(children) ? children({
    sortable: sortable,
    sortOrder: sortOrder,
    onSortClick: onSortClick,
    sorted: sorted,
    columnId: columnId
  }) : !(0, _utils.isElement)(children) && _react.default.createElement(_HeaderContent.HeaderContent, {
    onSortClick: onSortClick,
    sortable: sortable,
    sortOrder: sortOrder,
    sorted: sorted
  }, children));
};
Header.TextWrapper = _HeaderContent.TextWrapper;
Header.SortIcon = _HeaderContent.SortIcon;
Header.SortButton = _HeaderContent.SortButton;
var _default = exports.default = Header;