import _isNil from "ramda/src/isNil";
import _prop from "ramda/src/prop";
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; }
import React, { useContext, useEffect } from 'react';
import styled from 'styled-components';
import { isElement, isFunction } from '../../../common/utils';
import { Flexbox } from '../../..';
import { SORT_ORDER_ASCENDING, SORT_ORDER_DESCENDING, SORT_ORDER_NONE } from '../shared/constants';
import { ACTION_SET_INITIAL_SORTING, ACTION_SET_SORTING, useColumnData, useFlexCellProps } from '../shared/ColumnProvider';
import { HeaderContent, SortButton, SortIcon, TextWrapper } from './HeaderContent';
import { getPersistedSortOrder, getStylesForSizes, tableHasSavedPersistedSortOrder } from '../shared';
import { useFlexTable } from '../shared/FlexTableProvider';
import { getDensityPaddings } from '../shared/textUtils';
import { FlexTableContext } from '../shared/FlexTableProvider/FlexTableProvider';
import { setPersistedSortOrder } from '../shared/persistedSortOrder';
var SORT_ORDERS = [SORT_ORDER_NONE, SORT_ORDER_ASCENDING, 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(getDensityPaddings(density), "px !important;\n  padding-bottom: ").concat(getDensityPaddings(density), "px;\n");
};
var StyledFlexbox = styled(Flexbox).withConfig({
  displayName: "Header__StyledFlexbox",
  componentId: "sc-5wp0tw-0"
})(["overflow:hidden;", ""], 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 ? 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 = useFlexTable('density'),
    xs = _useFlexTable.xs,
    sm = _useFlexTable.sm,
    md = _useFlexTable.md,
    lg = _useFlexTable.lg,
    xl = _useFlexTable.xl;
  var contextData = useContext(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 = useColumnData(columnId),
    _useColumnData2 = _slicedToArray(_useColumnData, 2),
    columnState = _useColumnData2[0],
    columnDispatch = _useColumnData2[1];
  var storedSortOrder = persistSortingOrder ? getPersistedSortOrder(tableId) : null;
  var persistedSortOrder = storedSortOrder && storedSortOrder.columnId === columnId ? storedSortOrder.sortOrder : null;
  var savedSortOrderExists = persistSortingOrder && tableHasSavedPersistedSortOrder(tableId);
  var sortOrder = sortable ? getSortOrder(_prop('sortOrder', columnState), sortOrderProp, persistedSortOrder, savedSortOrderExists ? initialSortOrder : SORT_ORDER_NONE) : null;
  var ariaSorted = sortable ? {
    'aria-sort': sortOrder
  } : {};
  var cellFlexProps = useFlexCellProps(props);
  var controlledSort = sortOrderProp !== undefined;
  useEffect(function () {
    columnDispatch({
      type: ACTION_SET_INITIAL_SORTING,
      sortOrder: sortOrder,
      controlledSort: controlledSort
    });
  }, []);
  useEffect(function () {
    if (controlledSort) {
      columnDispatch({
        type: ACTION_SET_SORTING,
        sortOrder: sortOrderProp
      });
    }
  }, [sortOrderProp, controlledSort, columnDispatch]);
  var onSortClick = function onSortClick() {
    var newSortOrder = getNextSortOrder(sortOrder || initialSortOrder);
    onSort(columnId, newSortOrder);
    if (!controlledSort) {
      columnDispatch({
        type: ACTION_SET_SORTING,
        sortOrder: newSortOrder
      });
      setPersistedSortOrder(tableId, columnId, newSortOrder);
    }
  };
  var sorted = !_isNil(sortOrder) && sortOrder !== SORT_ORDER_NONE;
  return React.createElement(StyledFlexbox, _extends({
    className: className,
    role: "columnheader",
    $xs: xs,
    $sm: sm,
    $md: md,
    $lg: lg,
    $xl: xl
  }, ariaSorted, cellFlexProps), isElement(children) && children, isFunction(children) ? children({
    sortable: sortable,
    sortOrder: sortOrder,
    onSortClick: onSortClick,
    sorted: sorted,
    columnId: columnId
  }) : !isElement(children) && React.createElement(HeaderContent, {
    onSortClick: onSortClick,
    sortable: sortable,
    sortOrder: sortOrder,
    sorted: sorted
  }, children));
};
Header.TextWrapper = TextWrapper;
Header.SortIcon = SortIcon;
Header.SortButton = SortButton;
export default Header;