import * as React from 'react';
import { fromEvent, Subject, Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import { ActionItem } from '../../../components/ActionItem';
import { Tooltip } from '../../../components/tooltip/Tooltip';
import { eventLogger } from '../../../tracking/eventLogger';
import { ChatIcon } from '../../../util/icons'; // TODO: Switch to mdi icon
import { lprToRange, parseHash, toPositionOrRangeHash, toViewStateHashComponent } from '../../../util/url';
/**
 * A repository header action that toggles the visibility of the discussions panel.
 */
export class ToggleDiscussionsPanel extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.toggles = new Subject();
        this.subscriptions = new Subscription();
        this.onClick = () => this.toggles.next();
    }
    /**
     * Reports the current visibility (derived from the location).
     */
    static isVisible(location) {
        return parseHash(location.hash).viewState === 'discussions';
    }
    /**
     * Returns the location object (that can be passed to H.History's push/replace methods) that sets visibility to
     * the given value.
     */
    static locationWithVisibility(location, visible) {
        const hash = parseHash(location.hash);
        if (visible) {
            hash.viewState = 'discussions'; // defaults to last-viewed tab, or first tab
        }
        else {
            delete hash.viewState;
        }
        return { hash: toPositionOrRangeHash({ range: lprToRange(hash) }) + toViewStateHashComponent(hash.viewState) };
    }
    componentDidMount() {
        this.subscriptions.add(this.toggles.subscribe(() => {
            const visible = ToggleDiscussionsPanel.isVisible(this.props.location);
            eventLogger.log(visible ? 'HideDiscussionsPanel' : 'ShowDiscussionsPanel');
            this.props.history.push(ToggleDiscussionsPanel.locationWithVisibility(this.props.location, !visible));
            Tooltip.forceUpdate();
        }));
        // Toggle when the user presses 'alt+d' or 'opt+d'.
        this.subscriptions.add(fromEvent(window, 'keydown')
            .pipe(filter(event => event.altKey && event.key === 'd'))
            .subscribe(event => {
            event.preventDefault();
            this.toggles.next();
        }));
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        const visible = ToggleDiscussionsPanel.isVisible(this.props.location);
        return (React.createElement(ActionItem, { onSelect: this.onClick, "data-tooltip": `${visible ? 'Hide' : 'Show'} discussions (Alt+D/Opt+D)` },
            React.createElement(ChatIcon, { className: "icon-inline" })));
    }
}
//# sourceMappingURL=ToggleDiscussions.js.map