"use strict";
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 __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var react_dom_1 = __importDefault(require("react-dom"));
var prop_types_1 = __importDefault(require("prop-types"));
var lodash_1 = __importDefault(require("lodash"));
var classnames_1 = __importDefault(require("classnames"));
var EventBus_1 = __importDefault(require("../../../utils/EventBus"));
var LocalStorage_1 = require("../../../data/LocalStorage");
var GridSorter_1 = require("./GridSorter");
var index_en_US_1 = __importDefault(require("../../../../lang/common/index-en_US"));
var RESIZE_OVERLAY_ID = 'GridHeaderCellResizeOverlay';
var COLUMNS_KEY = 'columns';
var RESIZE_EVENT = 'GridHeaderCellResize';
var DEFAULT_MIN_WIDTH = 60;
var NON_SORTABLE_DEFAULT_MIN_WIDTH = 40;
var GridHeaderCell = /** @class */ (function (_super) {
    __extends(GridHeaderCell, _super);
    function GridHeaderCell() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            minWidth: null,
            resizing: null
        };
        _this.handleSiblingResize = function (localStoragePrefix) {
            var localStorage = _this.context.localStorage;
            var resizing = _this.state.resizing;
            if (resizing || !localStorage || localStoragePrefix !== localStorage.prefix) {
                return;
            }
            var cell = _this.cellRef || react_dom_1.default.findDOMNode(_this.gridSorterRef);
            if (!cell) {
                return;
            }
            var minWidth = _this.props.minWidth;
            if (!minWidth) {
                return;
            }
            var width = cell.clientWidth;
            if (!width) {
                // cell is not visible, ignore its width
                if (_this.state.minWidth) {
                    _this.setState({ minWidth: null });
                }
                return;
            }
            if (width <= minWidth) {
                if (minWidth !== _this.state.minWidth) {
                    _this.setState({ minWidth: minWidth });
                }
                else {
                    // Reset minWidth -> Render -> Re-calculate minWidth
                    _this.setState({ minWidth: null }, function () { return _this.handleSiblingResize(localStoragePrefix); });
                }
            }
            else if (_this.state.minWidth) {
                _this.setState({ minWidth: null });
            }
        };
        _this.startResizing = function (event) {
            event.stopPropagation();
            var cell = _this.getParentCell(event.target);
            if (!cell) {
                return;
            }
            var overlay = _this.createResizeOverlay();
            document.body.appendChild(overlay);
            document.addEventListener('mousemove', _this.resize);
            document.addEventListener('mouseup', _this.stopResizing);
            _this.setState({
                minWidth: null,
                resizing: {
                    x: event.pageX,
                    width: cell.clientWidth,
                    startWidth: cell.clientWidth
                }
            });
        };
        _this.resize = function (event) {
            event.stopPropagation();
            var _a = _this.props, minWidth = _a.minWidth, maxWidth = _a.maxWidth, isSortable = _a.isSortable;
            var resizing = _this.state.resizing;
            if (!minWidth) {
                minWidth = isSortable ? DEFAULT_MIN_WIDTH : NON_SORTABLE_DEFAULT_MIN_WIDTH;
            }
            if (resizing) {
                var width = resizing.startWidth - resizing.x + event.pageX;
                if (width < minWidth) {
                    width = minWidth;
                }
                else if (width > maxWidth) {
                    width = maxWidth;
                }
                if (width !== resizing.width) {
                    _this.setState({
                        minWidth: null,
                        resizing: __assign({}, resizing, { width: width })
                    }, _this.notifySiblings);
                }
            }
        };
        _this.stopResizing = function (event) {
            event.stopPropagation();
            var localStorage = _this.context.localStorage;
            var property = _this.props.property;
            var resizing = _this.state.resizing;
            if (resizing && localStorage && property) {
                var columns = localStorage.getItem(COLUMNS_KEY) || {};
                columns[property] = __assign({}, columns[property], { width: resizing.width });
                localStorage.setItem(COLUMNS_KEY, columns);
            }
            _this.cancelResizing();
            _this.setState({
                resizing: null
            });
        };
        _this.notifySiblings = function () {
            var localStorage = _this.context.localStorage;
            if (localStorage && localStorage.prefix) {
                EventBus_1.default.emit(RESIZE_EVENT, localStorage.prefix);
            }
        };
        _this.renderChildren = function (ariaDescription, skipContentForSR, ariaDescriptionId, children) {
            return (react_1.default.createElement("span", null,
                children && react_1.default.createElement("span", { "aria-hidden": skipContentForSR }, children),
                ariaDescription && (react_1.default.createElement("span", { className: "sr-only", id: ariaDescriptionId }, ariaDescription))));
        };
        return _this;
    }
    GridHeaderCell.prototype.componentDidMount = function () {
        EventBus_1.default.on(RESIZE_EVENT, this.handleSiblingResize);
        var localStorage = this.context.localStorage;
        if (localStorage && localStorage.prefix) {
            this.handleSiblingResize(localStorage.prefix);
        }
    };
    GridHeaderCell.prototype.componentWillUnmount = function () {
        EventBus_1.default.off(RESIZE_EVENT, this.handleSiblingResize);
        this.cancelResizing();
    };
    GridHeaderCell.prototype.getResizeColumnWidth = function () {
        var _a = this.state, resizing = _a.resizing, minWidth = _a.minWidth;
        if (resizing) {
            return resizing.width;
        }
        if (minWidth) {
            return minWidth;
        }
        var localStorage = this.context.localStorage;
        var property = this.props.property;
        if (localStorage && property) {
            var columns = localStorage.getItem(COLUMNS_KEY);
            if (columns && columns[property]) {
                return columns[property].width;
            }
        }
    };
    GridHeaderCell.prototype.getParentCell = function (element) {
        var cell = element;
        while (cell && cell.tagName !== 'TH' && cell.tagName !== 'TD') {
            cell = cell.parentNode;
        }
        return cell;
    };
    GridHeaderCell.prototype.createResizeOverlay = function () {
        var container = document.createElement('div');
        var overlay = document.createElement('div');
        container.id = RESIZE_OVERLAY_ID;
        container.className = 'bootstrap-rc';
        overlay.className = 'resizing-overlay resizing-overlay-ew';
        container.appendChild(overlay);
        return container;
    };
    GridHeaderCell.prototype.cancelResizing = function () {
        var overlay = document.getElementById(RESIZE_OVERLAY_ID);
        if (overlay) {
            overlay.parentNode.removeChild(overlay);
        }
        document.removeEventListener('mousemove', this.resize);
        document.removeEventListener('mouseup', this.stopResizing);
    };
    GridHeaderCell.prototype.isResizable = function () {
        var localStorage = this.context.localStorage;
        var _a = this.props, isResizable = _a.isResizable, property = _a.property;
        return !!(localStorage && isResizable && property);
    };
    GridHeaderCell.prototype.renderResizeHandler = function () {
        if (this.props.noRightBorder) {
            return null;
        }
        var isResizable = this.isResizable();
        var className = classnames_1.default('resize-handler', { active: isResizable });
        return (react_1.default.createElement("span", { className: className, onMouseDown: isResizable ? this.startResizing : null }));
    };
    GridHeaderCell.prototype.renderPrepend = function (prepend) {
        if (!prepend) {
            return null;
        }
        return react_1.default.createElement("span", null, prepend);
    };
    GridHeaderCell.prototype.renderAppend = function (append) {
        if (!append) {
            return null;
        }
        return react_1.default.createElement("span", { className: "column-header-append" }, append);
    };
    GridHeaderCell.prototype.renderCellContent = function (prepend, children, append) {
        return (react_1.default.createElement("div", { className: "column-header-content" },
            this.renderPrepend(prepend),
            react_1.default.createElement("div", { className: "column-header-label text-overflow" }, children),
            this.renderAppend(append)));
    };
    GridHeaderCell.prototype.render = function () {
        var _this = this;
        var _a = this.props, isSortable = _a.isSortable, _isResizable = _a.isResizable, append = _a.append, _minWidth = _a.minWidth, maxWidth = _a.maxWidth, noRightBorder = _a.noRightBorder, ariaDescription = _a.ariaDescription, ariaDescriptionId = _a.ariaDescriptionId, skipContentForSR = _a.skipContentForSR, displayName = _a.displayName, className = _a.className, style = _a.style, children = _a.children, props = __rest(_a, ["isSortable", "isResizable", "append", "minWidth", "maxWidth", "noRightBorder", "ariaDescription", "ariaDescriptionId", "skipContentForSR", "displayName", "className", "style", "children"]);
        var _b = this.state, resizing = _b.resizing, minWidth = _b.minWidth;
        var child = this.renderChildren(ariaDescription, skipContentForSR, ariaDescriptionId, children);
        var isResizable = this.isResizable();
        var prepend = this.renderResizeHandler();
        var classNames = classnames_1.default(className, {
            resizable: isResizable,
            resizing: isResizable && resizing
        });
        var styles = style;
        if (isResizable) {
            var width = this.getResizeColumnWidth();
            if (width) {
                styles = __assign({}, styles, { width: width });
            }
        }
        else if (minWidth) {
            styles = __assign({}, styles, { width: minWidth });
        }
        if (isSortable) {
            var GridSorterTS = GridSorter_1.GridSorter;
            return (react_1.default.createElement(GridSorterTS, __assign({ ref: function (th) { return (_this.gridSorterRef = th); }, displayName: (displayName || children), className: classNames, style: styles }, props, { append: append, prepend: prepend }), child));
        }
        var testAutomationId = props.testAutomationId, restProps = __rest(props, ["testAutomationId"]);
        var tableHeaderProps = lodash_1.default.omit(restProps, Object.keys(GridHeaderCell.defaultProps));
        return (react_1.default.createElement("th", __assign({ ref: function (cell) { return (_this.cellRef = cell); }, "data-test-automation-id": testAutomationId, className: classNames, style: styles }, tableHeaderProps), this.renderCellContent(prepend, children, append)));
    };
    GridHeaderCell.propTypes = {
        // ...GridSorter.propTypes,
        isSortable: prop_types_1.default.bool,
        isResizable: prop_types_1.default.bool,
        append: prop_types_1.default.node,
        minWidth: prop_types_1.default.number,
        maxWidth: prop_types_1.default.number,
        ariaDescription: prop_types_1.default.string,
        ariaDescriptionId: prop_types_1.default.string,
        skipContentForSR: prop_types_1.default.bool,
        noRightBorder: prop_types_1.default.bool
    };
    GridHeaderCell.defaultProps = {
        // ...GridSorter.defaultProps,
        isSortable: true,
        isResizable: false,
        append: null,
        minWidth: 0,
        maxWidth: 500,
        skipContentForSR: false,
        ariaDescriptionId: null,
        ariaDescription: '',
        noRightBorder: false,
        get ascendingText() {
            return index_en_US_1.default.SORT_BY_ASCENDING;
        },
        get descendingText() {
            return index_en_US_1.default.SORT_BY_DESCENDING;
        },
        get sorterTitleText() {
            return index_en_US_1.default.CLICK_TO_SORT;
        }
    };
    GridHeaderCell.contextTypes = {
        localStorage: prop_types_1.default.instanceOf(LocalStorage_1.LocalStorage)
    };
    return GridHeaderCell;
}(react_1.default.Component));
exports.GridHeaderCell = GridHeaderCell;
//# sourceMappingURL=GridHeaderCell.js.map