var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import * as classnames from "classnames";
import * as _ from "lodash";
import * as React from "react";
import * as PropTypes from "prop-types";
import * as tablePropTypes from "./tablePropTypes";
import Cell from "./Cell";
import { Column } from "./Column";
import Footer from "./Footer";
import Header from "./Header";
import MorePropTypes from "../utils/MorePropTypes";
import sortDirection from "./sortDirection";
import "./Table.less";
var DEFAULT_PAGE_SIZE = 10;
export var DEFAULT_VISIBLE_PAGE_RANGE_SIZE = 5;
var propTypes = {
    children: PropTypes.arrayOf(MorePropTypes.instanceOfComponent(Column)),
    className: PropTypes.string,
    data: PropTypes.array,
    filter: PropTypes.func,
    fixed: PropTypes.bool,
    initialPage: tablePropTypes.pageNumber,
    initialSortState: tablePropTypes.sortState,
    firstSortDirection: tablePropTypes.sortDirection,
    onPageChange: PropTypes.func,
    onRowClick: PropTypes.func,
    onRowMouseOver: PropTypes.func,
    onSortChange: PropTypes.func,
    onViewChange: PropTypes.func,
    pageSize: PropTypes.number,
    paginated: PropTypes.bool,
    visiblePageRangeSize: PropTypes.number,
    rowIDFn: PropTypes.func.isRequired,
    rowClassNameFn: PropTypes.func,
    noDataContent: PropTypes.node,
    // these must all be set together
    lazy: PropTypes.bool,
    getData: PropTypes.func,
    numRows: PropTypes.number,
};
var defaultProps = {
    onPageChange: function () { },
    onSortChange: function () { },
    pageSize: DEFAULT_PAGE_SIZE,
    visiblePageRangeSize: DEFAULT_VISIBLE_PAGE_RANGE_SIZE,
    firstSortDirection: sortDirection.ASCENDING,
};
export var cssClass = {
    BODY: "Table--body",
    CLICKABLE_ROW: "Table--clickable_row",
    FIXED: "Table--fixed",
    NO_DATA: "Table--no_data_cell",
    NO_DATA_CONTENT: "Table--no_data_cell_with_content",
    ROW: "Table--row",
    TABLE: "Table",
};
var Table = /** @class */ (function (_super) {
    __extends(Table, _super);
    function Table(props) {
        var _this = _super.call(this, props) || this;
        if (props.lazy) {
            for (var _i = 0, _a = ["data", "filter", "initialPage"]; _i < _a.length; _i++) {
                var p = _a[_i];
                if (props[p]) {
                    console.error("Table: prop \"" + p + "\" may not be set if \"lazy\"");
                }
            }
            if (!props.getData) {
                console.error('Table: prop "getData" must be set if "lazy"');
            }
        }
        else {
            if (!props.data) {
                console.error('Table: prop "data" must be set if not "lazy"');
            }
            for (var _b = 0, _c = ["getData", "numRows"]; _b < _c.length; _b++) {
                var p = _c[_b];
                if (props[p]) {
                    console.error("Table: prop \"" + p + "\" may not be set if not \"lazy\"");
                }
            }
        }
        _this.state = {
            currentPage: props.initialPage || 1,
            sortState: props.initialSortState,
            // lazy table state
            lazyPages: [],
            pageLoading: false,
            allLoaded: false,
        };
        // the epoch is incremented on calls to this.lazyReset, so we know to throw
        // out in-progress fetches if the table gets reset (see this._fetchLazy).
        _this._epoch = 0;
        return _this;
    }
    Table.prototype.componentDidMount = function () {
        this._isMounted = true;
        if (this.props.lazy) {
            this._fetchLazy(0);
        }
    };
    Table.prototype.componentWillUnmount = function () {
        this._isMounted = false;
    };
    /**
     * @param {number} page - 1-based index of the page to select.
     */
    Table.prototype.setCurrentPage = function (page) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, onPageChange, onViewChange, lazy, _b, currentPage, pageLoading, pageIdx;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = this.props, onPageChange = _a.onPageChange, onViewChange = _a.onViewChange, lazy = _a.lazy;
                        _b = this.state, currentPage = _b.currentPage, pageLoading = _b.pageLoading;
                        if (page === currentPage || pageLoading) {
                            return [2 /*return*/];
                        }
                        if (!lazy) return [3 /*break*/, 2];
                        pageIdx = page - 1;
                        return [4 /*yield*/, this._fetchLazy(pageIdx)];
                    case 1:
                        _c.sent();
                        _c.label = 2;
                    case 2:
                        this.setState({ currentPage: page }, function () {
                            onPageChange(page);
                            if (onViewChange) {
                                var displayedData = _this._getDisplayedData().displayedData;
                                onViewChange(displayedData);
                            }
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    Table.prototype._fetchLazy = function (pageIdx) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, pageSize, getData, rowIDFn, lazyPages, startEpoch, newPages, idx, query, lastPage, pageData;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.props, pageSize = _a.pageSize, getData = _a.getData, rowIDFn = _a.rowIDFn;
                        lazyPages = this.state.lazyPages;
                        // if we've already fetched the page, no need to do anything here -- it's
                        // cached
                        if (pageIdx < lazyPages.length) {
                            return [2 /*return*/];
                        }
                        startEpoch = this._epoch;
                        this.setState({ pageLoading: true });
                        newPages = lazyPages.slice(0);
                        idx = lazyPages.length;
                        _b.label = 1;
                    case 1:
                        if (!(idx <= pageIdx)) return [3 /*break*/, 4];
                        query = { pageSize: pageSize };
                        // the first page shouldn't have a startingAfter parameter
                        if (idx !== 0) {
                            lastPage = newPages[idx - 1];
                            query.startingAfter = rowIDFn(lastPage[lastPage.length - 1]);
                        }
                        return [4 /*yield*/, getData(query)];
                    case 2:
                        pageData = _b.sent();
                        // Check if we should bail out to prevent updating state on an unmounted component.
                        if (!this._isMounted) {
                            return [2 /*return*/];
                        }
                        newPages.push(pageData);
                        _b.label = 3;
                    case 3:
                        idx++;
                        return [3 /*break*/, 1];
                    case 4:
                        if (this._epoch !== startEpoch) {
                            // the table was reset while we were fetching, so we don't want to
                            // actually insert our data
                            return [2 /*return*/];
                        }
                        if (newPages[newPages.length - 1].length < pageSize) {
                            this.setState({ allLoaded: true });
                            if (newPages[newPages.length - 1].length === 0) {
                                // remove the last page if it's empty (this happens if the number of
                                // rows is divisible by the page size)
                                newPages.splice(-1);
                            }
                        }
                        this.setState({ lazyPages: newPages, pageLoading: false });
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Resets all lazily-loaded data. Call this if you change the backing data
     * behind the `getData` function (i.e. apply a search filter).
     */
    Table.prototype.lazyReset = function () {
        var _this = this;
        if (this.props.lazy) {
            this._epoch++;
            this.setCurrentPage(1);
            this.setState({ lazyPages: [], allLoaded: false }, function () {
                _this._fetchLazy(0);
            });
        }
    };
    Table.prototype._getColumn = function (columnID) {
        return _.find(React.Children.toArray(this.props.children), function (column) { return column.props.id === columnID; });
    };
    Table.prototype._toggleSort = function (columnID) {
        var _this = this;
        var oldSortState = this.state.sortState;
        var newSortState = {
            columnID: columnID,
            direction: this.props.firstSortDirection,
        };
        if (oldSortState && oldSortState.columnID === columnID) {
            newSortState.direction =
                oldSortState.direction === sortDirection.ASCENDING
                    ? sortDirection.DESCENDING
                    : sortDirection.ASCENDING;
        }
        // Reset to 1st page since table sort has changed.
        this.setCurrentPage(1);
        this.setState({ sortState: newSortState }, function () {
            _this.props.onSortChange(_this.state.sortState);
            if (_this.props.onViewChange) {
                var displayedData = _this._getDisplayedData().displayedData;
                _this.props.onViewChange(displayedData);
            }
        });
        this.lazyReset();
    };
    Table.prototype._getSynchronousData = function () {
        var _a = this.props, data = _a.data, filter = _a.filter, pageSize = _a.pageSize, paginated = _a.paginated;
        var _b = this.state, currentPage = _b.currentPage, sortState = _b.sortState;
        var displayedData = _(data);
        if (filter) {
            displayedData = displayedData.filter(filter);
        }
        if (sortState) {
            var sortedColumn_1 = this._getColumn(sortState.columnID);
            // sortedColumn might not exist if a column is removed from the table
            // dynamically. in this case, just ignore the sort state.
            if (sortedColumn_1) {
                displayedData = displayedData.sortBy(function (row) {
                    var value = sortedColumn_1.props.sortValueFn(row);
                    if (typeof value === "string") {
                        value = value.trim().toLowerCase();
                    }
                    return value;
                });
                if (sortState.direction === sortDirection.DESCENDING) {
                    displayedData = displayedData.reverse();
                }
            }
        }
        displayedData = displayedData.value();
        var pages = [displayedData];
        if (paginated) {
            pages = _.chunk(displayedData, pageSize);
        }
        if (pages.length === 0) {
            // Chunking will return 0 pages if the data array is empty. Since we always show at least one
            // page of (potentially empty) data, add an empty page by default.
            pages = [[]];
        }
        var numPages = pages.length;
        var idx = Math.min(currentPage, numPages) - 1;
        return { displayedData: pages[idx], numPages: numPages };
    };
    Table.prototype._getLazyData = function () {
        var _a = this.props, numRows = _a.numRows, pageSize = _a.pageSize;
        var _b = this.state, currentPage = _b.currentPage, lazyPages = _b.lazyPages;
        var numPages;
        if (numRows != null) {
            numPages = Math.max(Math.ceil(numRows / pageSize), 1);
        }
        else {
            if (lazyPages.length === 0) {
                numPages = 1;
            }
            else {
                numPages = lazyPages.length;
            }
        }
        var idx = Math.min(currentPage, numPages) - 1;
        if (idx < lazyPages.length) {
            return { displayedData: lazyPages[idx], numPages: numPages };
        }
        return { displayedData: [], numPages: numPages };
    };
    Table.prototype._getDisplayedData = function () {
        if (!this.props.lazy) {
            return this._getSynchronousData();
        }
        return this._getLazyData();
    };
    Table.prototype.render = function () {
        var _this = this;
        var _a = this.props, children = _a.children, className = _a.className, fixed = _a.fixed, paginated = _a.paginated, rowIDFn = _a.rowIDFn, rowClassNameFn = _a.rowClassNameFn, onRowClick = _a.onRowClick, onRowMouseOver = _a.onRowMouseOver, noDataContent = _a.noDataContent, visiblePageRangeSize = _a.visiblePageRangeSize;
        var _b = this.props, lazy = _b.lazy, numRows = _b.numRows;
        var _c = this.state, currentPage = _c.currentPage, sortState = _c.sortState, pageLoading = _c.pageLoading, allLoaded = _c.allLoaded;
        var columns = _.compact(React.Children.toArray(children));
        if (columns.length < 2 && process.env.NODE_ENV !== "production") {
            console.error("Table requires at least 2 columns. Consider using the List component instead.");
        }
        var _d = this._getDisplayedData(), displayedData = _d.displayedData, numPages = _d.numPages;
        var displayedPage = Math.min(currentPage, numPages);
        var disableSort = numPages <= 1 && displayedData.length <= 1;
        return (React.createElement("table", { className: classnames(cssClass.TABLE, fixed && cssClass.FIXED, className) },
            React.createElement(Header, { disableSort: disableSort, onSortChange: function (columnID) { return _this._toggleSort(columnID); }, sortState: sortState }, columns),
            React.createElement("tbody", { className: cssClass.BODY }, displayedData.length === 0 ? (React.createElement("tr", { className: cssClass.ROW }, noDataContent ? (React.createElement(Cell, { className: cssClass.NO_DATA_CONTENT, colSpan: columns.length, noWrap: true }, noDataContent)) : (React.createElement(Cell, { className: cssClass.NO_DATA, colSpan: columns.length, noWrap: true }, !pageLoading && "NO DATA")))) : (displayedData.map(function (rowData) { return (React.createElement("tr", { className: classnames(cssClass.ROW, onRowClick && cssClass.CLICKABLE_ROW, rowClassNameFn && rowClassNameFn(rowData)), key: rowIDFn(rowData), onClick: function (e) { return onRowClick && onRowClick(e, rowIDFn(rowData), rowData); }, tabIndex: onRowClick ? 0 : undefined, onMouseOver: function (e) { return onRowMouseOver && onRowMouseOver(e, rowIDFn(rowData), rowData); } }, columns.map(function (_a) {
                var col = _a.props;
                return (React.createElement(Cell, { className: getCellClassName(col, rowData), key: col.id, noWrap: col.noWrap }, col.cell.renderer(rowData)));
            }))); }))),
            paginated && (React.createElement(Footer, { currentPage: displayedPage, onPageChange: function (newPage) { return _this.setCurrentPage(newPage); }, numColumns: columns.length, numPages: numPages, showLastPage: !lazy, visiblePageRangeSize: visiblePageRangeSize, isLoading: pageLoading, lengthUnknown: lazy && numRows == null && !allLoaded }))));
    };
    Table.propTypes = propTypes;
    Table.defaultProps = defaultProps;
    Table.Column = Column;
    Table.sortDirection = sortDirection;
    return Table;
}(React.Component));
export { Table };
function getCellClassName(columnProps, rowData) {
    var className = columnProps.cell.className;
    if (typeof className === "function") {
        return className(rowData);
    }
    return className;
}
