import * as tslib_1 from "tslib";
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BaseComponent, assign, autobind, css, shallowCompare, getNativeProps, divProperties } from '../../Utilities';
import { CheckboxVisibility } from './DetailsList.types';
import { DetailsRowCheck } from './DetailsRowCheck';
import { GroupSpacer } from '../GroupedList/GroupSpacer';
import { DetailsRowFields } from './DetailsRowFields';
import { FocusZone, FocusZoneDirection } from '../../FocusZone';
import { SelectionMode, SELECTION_CHANGE } from '../../utilities/selection/interfaces';
import { CollapseAllVisibility } from '../../GroupedList';
import { AnimationClassNames } from '../../Styling';
import * as stylesImport from './DetailsRow.scss';
var styles = stylesImport;
import * as checkStylesImport from './DetailsRowCheck.scss';
var checkStyles = checkStylesImport;
var DEFAULT_DROPPING_CSS_CLASS = 'is-dropping';
var DetailsRow = /** @class */ (function (_super) {
    tslib_1.__extends(DetailsRow, _super);
    function DetailsRow(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            selectionState: _this._getSelectionState(props),
            columnMeasureInfo: undefined,
            isDropping: false,
            groupNestingDepth: props.groupNestingDepth
        };
        _this._hasSetFocus = false;
        _this._droppingClassNames = '';
        _this._updateDroppingState = _this._updateDroppingState.bind(_this);
        _this._onToggleSelection = _this._onToggleSelection.bind(_this);
        return _this;
    }
    DetailsRow.prototype.componentDidMount = function () {
        var dragDropHelper = this.props.dragDropHelper;
        if (dragDropHelper) {
            this._dragDropSubscription = dragDropHelper.subscribe(this._root, this._events, this._getRowDragDropOptions());
        }
        this._events.on(this.props.selection, SELECTION_CHANGE, this._onSelectionChanged);
        if (this.props.onDidMount && this.props.item) {
            // If the item appears later, we should wait for it before calling this method.
            this._hasMounted = true;
            this.props.onDidMount(this);
        }
    };
    DetailsRow.prototype.componentDidUpdate = function (previousProps) {
        var state = this.state;
        var _a = this.props, item = _a.item, onDidMount = _a.onDidMount;
        var columnMeasureInfo = state.columnMeasureInfo;
        if (this.props.itemIndex !== previousProps.itemIndex ||
            this.props.item !== previousProps.item ||
            this.props.dragDropHelper !== previousProps.dragDropHelper) {
            if (this._dragDropSubscription) {
                this._dragDropSubscription.dispose();
                delete this._dragDropSubscription;
            }
            if (this.props.dragDropHelper) {
                this._dragDropSubscription = this.props.dragDropHelper.subscribe(this._root, this._events, this._getRowDragDropOptions());
            }
        }
        if (columnMeasureInfo && columnMeasureInfo.index >= 0) {
            var newWidth = this.refs.cellMeasurer.getBoundingClientRect().width;
            columnMeasureInfo.onMeasureDone(newWidth);
            this.setState({
                columnMeasureInfo: undefined
            });
        }
        if (item && onDidMount && !this._hasMounted) {
            this._hasMounted = true;
            onDidMount(this);
        }
    };
    DetailsRow.prototype.componentWillUnmount = function () {
        var _a = this.props, item = _a.item, onWillUnmount = _a.onWillUnmount;
        // Only call the onWillUnmount callback if we have an item.
        if (onWillUnmount && item) {
            onWillUnmount(this);
        }
        if (this._dragDropSubscription) {
            this._dragDropSubscription.dispose();
            delete this._dragDropSubscription;
        }
    };
    DetailsRow.prototype.componentWillReceiveProps = function (newProps) {
        this.setState({
            selectionState: this._getSelectionState(newProps),
            groupNestingDepth: newProps.groupNestingDepth
        });
    };
    DetailsRow.prototype.render = function () {
        var _a = this.props, className = _a.className, columns = _a.columns, dragDropEvents = _a.dragDropEvents, item = _a.item, itemIndex = _a.itemIndex, _b = _a.onRenderCheck, onRenderCheck = _b === void 0 ? this._onRenderCheck : _b, onRenderItemColumn = _a.onRenderItemColumn, selectionMode = _a.selectionMode, viewport = _a.viewport, checkboxVisibility = _a.checkboxVisibility, getRowAriaLabel = _a.getRowAriaLabel, getRowAriaDescribedBy = _a.getRowAriaDescribedBy, checkButtonAriaLabel = _a.checkButtonAriaLabel, checkboxCellClassName = _a.checkboxCellClassName, selection = _a.selection;
        var _c = this.state, columnMeasureInfo = _c.columnMeasureInfo, isDropping = _c.isDropping, groupNestingDepth = _c.groupNestingDepth;
        var _d = this.state.selectionState, _e = _d.isSelected, isSelected = _e === void 0 ? false : _e, _f = _d.isSelectionModal, isSelectionModal = _f === void 0 ? false : _f;
        var isDraggable = Boolean(dragDropEvents && dragDropEvents.canDrag && dragDropEvents.canDrag(item));
        var droppingClassName = isDropping ? (this._droppingClassNames ? this._droppingClassNames : DEFAULT_DROPPING_CSS_CLASS) : '';
        var ariaLabel = getRowAriaLabel ? getRowAriaLabel(item) : null;
        var ariaDescribedBy = getRowAriaDescribedBy ? getRowAriaDescribedBy(item) : undefined;
        var canSelect = selection.canSelectItem(item);
        var isContentUnselectable = selectionMode === SelectionMode.multiple;
        var showCheckbox = selectionMode !== SelectionMode.none && checkboxVisibility !== CheckboxVisibility.hidden;
        return (React.createElement(FocusZone, tslib_1.__assign({}, getNativeProps(this.props, divProperties), { direction: FocusZoneDirection.horizontal, ref: this._onRootRef, componentRef: this._resolveRef('_focusZone'), role: 'row', "aria-label": ariaLabel, ariaDescribedBy: ariaDescribedBy, className: css('ms-DetailsRow', className, AnimationClassNames.fadeIn400, styles.root, checkStyles.owner, droppingClassName, (_g = {},
                _g["is-contentUnselectable " + styles.rootIsContentUnselectable] = isContentUnselectable,
                _g["is-selected " + checkStyles.isSelected + " " + styles.rootIsSelected] = isSelected,
                _g[styles.anySelected + " " + checkStyles.anySelected] = isSelectionModal,
                _g["is-check-visible " + checkStyles.isVisible] = checkboxVisibility === CheckboxVisibility.always,
                _g)), "data-is-focusable": true, "data-selection-index": itemIndex, "data-item-index": itemIndex, "aria-rowindex": itemIndex, "data-is-draggable": isDraggable, draggable: isDraggable, "data-automationid": 'DetailsRow', style: { minWidth: viewport ? viewport.width : 0 }, "aria-selected": isSelected, allowFocusRoot: true }),
            showCheckbox && (React.createElement("div", { role: 'gridcell', "aria-colindex": 0, "data-selection-toggle": true, className: css('ms-DetailsRow-cell', 'ms-DetailsRow-cellCheck', checkStyles.owner, styles.cell, styles.checkCell, checkboxCellClassName) }, onRenderCheck({
                selected: isSelected,
                anySelected: isSelectionModal,
                title: checkButtonAriaLabel,
                canSelect: canSelect
            }))),
            GroupSpacer({ count: groupNestingDepth - (this.props.collapseAllVisibility === CollapseAllVisibility.hidden ? 1 : 0) }),
            item && (React.createElement(DetailsRowFields, { columns: columns, item: item, itemIndex: itemIndex, columnStartIndex: showCheckbox ? 1 : 0, onRenderItemColumn: onRenderItemColumn })),
            columnMeasureInfo && (React.createElement("span", { role: 'presentation', className: css('ms-DetailsRow-cellMeasurer ms-DetailsRow-cell', styles.cellMeasurer, styles.cell), ref: 'cellMeasurer' },
                React.createElement(DetailsRowFields, { columns: [columnMeasureInfo.column], item: item, itemIndex: itemIndex, columnStartIndex: (showCheckbox ? 1 : 0) + columns.length, onRenderItemColumn: onRenderItemColumn }))),
            React.createElement("span", { role: 'checkbox', className: css(styles.checkCover), "aria-checked": isSelected, "data-selection-toggle": true })));
        var _g;
    };
    /**
     * measure cell at index. and call the call back with the measured cell width when finish measure
     *
     * @param {number} index (the cell index)
     * @param {(width: number) => void} onMeasureDone (the call back function when finish measure)
     */
    DetailsRow.prototype.measureCell = function (index, onMeasureDone) {
        var column = assign({}, this.props.columns[index]);
        column.minWidth = 0;
        column.maxWidth = 999999;
        delete column.calculatedWidth;
        this.setState({
            columnMeasureInfo: {
                index: index,
                column: column,
                onMeasureDone: onMeasureDone
            }
        });
    };
    DetailsRow.prototype.focus = function () {
        return !!this._focusZone && this._focusZone.focus();
    };
    DetailsRow.prototype._onRenderCheck = function (props) {
        return React.createElement(DetailsRowCheck, tslib_1.__assign({}, props));
    };
    DetailsRow.prototype._getSelectionState = function (props) {
        var itemIndex = props.itemIndex, selection = props.selection;
        return {
            isSelected: selection.isIndexSelected(itemIndex),
            isSelectionModal: !!selection.isModal && selection.isModal()
        };
    };
    DetailsRow.prototype._onSelectionChanged = function () {
        var selectionState = this._getSelectionState(this.props);
        if (!shallowCompare(selectionState, this.state.selectionState)) {
            this.setState({
                selectionState: selectionState
            });
        }
    };
    DetailsRow.prototype._onToggleSelection = function () {
        var selection = this.props.selection;
        selection.toggleIndexSelected(this.props.itemIndex);
    };
    DetailsRow.prototype._onRootRef = function (focusZone) {
        if (focusZone) {
            // Need to resolve the actual DOM node, not the component. The element itself will be used for drag/drop and focusing.
            this._root = ReactDOM.findDOMNode(focusZone);
        }
        else {
            this._root = undefined;
        }
    };
    DetailsRow.prototype._getRowDragDropOptions = function () {
        var _a = this.props, item = _a.item, itemIndex = _a.itemIndex, dragDropEvents = _a.dragDropEvents, eventsToRegister = _a.eventsToRegister;
        var options = {
            eventMap: eventsToRegister,
            selectionIndex: itemIndex,
            context: { data: item, index: itemIndex },
            canDrag: dragDropEvents.canDrag,
            canDrop: dragDropEvents.canDrop,
            onDragStart: dragDropEvents.onDragStart,
            updateDropState: this._updateDroppingState,
            onDrop: dragDropEvents.onDrop,
            onDragEnd: dragDropEvents.onDragEnd,
        };
        return options;
    };
    /**
     * update isDropping state based on the input value, which is used to change style during drag and drop
     *
     * when change to true, that means drag enter. we will add default dropping class name
     * or the custom dropping class name (return result from onDragEnter) to the root elemet.
     *
     * when change to false, that means drag leave. we will remove the dropping class name from root element.
     *
     * @private
     * @param {boolean} newValue (new isDropping state value)
     * @param {DragEvent} event (the event trigger dropping state change which can be dragenter, dragleave etc)
     */
    DetailsRow.prototype._updateDroppingState = function (newValue, event) {
        var _a = this.state, selectionState = _a.selectionState, isDropping = _a.isDropping;
        var _b = this.props, dragDropEvents = _b.dragDropEvents, item = _b.item;
        if (!newValue) {
            if (dragDropEvents.onDragLeave) {
                dragDropEvents.onDragLeave(item, event);
            }
        }
        else {
            if (dragDropEvents.onDragEnter) {
                this._droppingClassNames = dragDropEvents.onDragEnter(item, event);
            }
        }
        if (isDropping !== newValue) {
            this.setState({ selectionState: selectionState, isDropping: newValue });
        }
    };
    tslib_1.__decorate([
        autobind
    ], DetailsRow.prototype, "_onRootRef", null);
    return DetailsRow;
}(BaseComponent));
export { DetailsRow };
//# sourceMappingURL=DetailsRow.js.map