import { LoadingSpinner } from '@sourcegraph/react-loading-spinner';
import AddIcon from 'mdi-react/AddIcon';
import AutoFixIcon from 'mdi-react/AutoFixIcon';
import HelpCircleOutlineIcon from 'mdi-react/HelpCircleOutlineIcon';
import * as React from 'react';
import { Redirect } from 'react-router';
import { Link } from 'react-router-dom';
import { Subject, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { currentUser } from '../../auth';
import { siteFlags } from '../../site/backend';
import { eventLogger } from '../../tracking/eventLogger';
import { observeSavedQueries } from '../backend';
import { ExampleSearches } from './ExampleSearches';
import { SavedQuery } from './SavedQuery';
import { SavedQueryCreateForm } from './SavedQueryCreateForm';
const EXAMPLE_SEARCHES_CLOSED_KEY = 'example-searches-closed';
export class SavedQueries extends React.Component {
    constructor() {
        super(...arguments);
        this.state = {
            savedQueries: [],
            isCreating: false,
            loading: true,
            user: null,
            isViewingExamples: window.context.sourcegraphDotComMode
                ? false
                : localStorage.getItem(EXAMPLE_SEARCHES_CLOSED_KEY) !== 'true',
            exampleQuery: null,
            disableBuiltInSearches: false,
        };
        this.componentUpdates = new Subject();
        this.subscriptions = new Subscription();
        this.toggleCreating = () => {
            eventLogger.log('SavedQueriesToggleCreating', { queries: { creating: !this.state.isCreating } });
            this.setState(state => ({ isCreating: !state.isCreating, exampleQuery: null, isViewingExamples: false }));
        };
        this.toggleExamples = () => {
            eventLogger.log('SavedQueriesToggleExamples', { queries: { viewingExamples: !this.state.isViewingExamples } });
            this.setState(state => ({
                isViewingExamples: !state.isViewingExamples,
                exampleQuery: null,
                isCreating: false,
            }), () => {
                if (!this.state.isViewingExamples && localStorage.getItem(EXAMPLE_SEARCHES_CLOSED_KEY) !== 'true') {
                    localStorage.setItem(EXAMPLE_SEARCHES_CLOSED_KEY, 'true');
                }
            });
        };
        this.onExampleSelected = (query) => {
            eventLogger.log('SavedQueryExampleSelected', { queries: { example: query } });
            this.setState({ isViewingExamples: false, isCreating: true, exampleQuery: query });
        };
        this.onDidCreateSavedQuery = () => {
            eventLogger.log('SavedQueryCreated');
            this.setState({ isCreating: false, exampleQuery: null });
        };
        this.onDidDuplicateSavedQuery = () => {
            eventLogger.log('SavedQueryDuplicated');
        };
        this.onDidClickQueryHelp = () => {
            eventLogger.log('SavedQueriesHelpButtonClicked');
        };
    }
    componentDidMount() {
        const isHomepage = this.props.location.pathname === '/search';
        this.subscriptions.add(observeSavedQueries()
            .pipe(map(savedQueries => ({
            savedQueries: savedQueries.filter(query => !isHomepage || query.showOnHomepage).sort((a, b) => {
                if (a.description < b.description) {
                    return -1;
                }
                if (a.description === b.description && a.index < b.index) {
                    return -1;
                }
                return 1;
            }),
            loading: false,
        })))
            .subscribe(newState => this.setState(newState), err => console.error(err)));
        this.subscriptions.add(siteFlags
            .pipe(map(({ disableBuiltInSearches }) => disableBuiltInSearches))
            .subscribe(disableBuiltInSearches => {
            this.setState({
                // TODO: Remove the need to check sourcegraphDotComMode by adding this to config
                disableBuiltInSearches: window.context.sourcegraphDotComMode || disableBuiltInSearches,
            });
        }));
        this.subscriptions.add(currentUser.subscribe(user => this.setState({ user })));
    }
    componentWillReceiveProps(newProps) {
        this.componentUpdates.next(newProps);
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        if (this.state.loading) {
            return React.createElement(LoadingSpinner, null);
        }
        const isHomepage = this.props.location.pathname === '/search';
        const isPanelOpen = this.state.isViewingExamples || this.state.isCreating;
        // If not logged in, redirect to sign in
        if (!this.state.user && !isHomepage) {
            const newUrl = new URL(window.location.href);
            // Return to the current page after sign up/in.
            newUrl.searchParams.set('returnTo', window.location.href);
            return React.createElement(Redirect, { to: '/sign-up' + newUrl.search });
        }
        return (React.createElement("div", { className: "saved-queries" },
            !isHomepage && (React.createElement("div", null,
                React.createElement("div", { className: "saved-queries__header" },
                    React.createElement("h3", null, !isPanelOpen && 'Saved searches'),
                    React.createElement("div", { className: "saved-queries__actions" },
                        !this.state.disableBuiltInSearches && (React.createElement("button", { className: "btn btn-link", onClick: this.toggleExamples, disabled: this.state.isViewingExamples },
                            React.createElement(AutoFixIcon, { className: "icon-inline" }),
                            " Discover built-in searches")),
                        React.createElement("button", { className: "btn btn-link", onClick: this.toggleCreating, disabled: this.state.isCreating },
                            React.createElement(AddIcon, { className: "icon-inline" }),
                            " Add new search"),
                        React.createElement("a", { href: "https://about.sourcegraph.com/docs/search/saved-searches", onClick: this.onDidClickQueryHelp, className: "btn btn-link", target: "_blank" },
                            React.createElement(HelpCircleOutlineIcon, { className: "icon-inline" }),
                            " Help"))),
                this.state.isCreating && (React.createElement(SavedQueryCreateForm, { user: this.props.user, onDidCreate: this.onDidCreateSavedQuery, onDidCancel: this.toggleCreating, values: this.state.exampleQuery || {} })))),
            React.createElement("div", null,
                !this.props.hideExampleSearches &&
                    !this.state.isCreating &&
                    this.state.isViewingExamples && (React.createElement(ExampleSearches, { isLightTheme: this.props.isLightTheme, onClose: this.toggleExamples, onExampleSelected: this.onExampleSelected })),
                !this.state.disableBuiltInSearches &&
                    !this.props.hideExampleSearches &&
                    isPanelOpen && (React.createElement("div", { className: "saved-queries__header saved-queries__space" },
                    React.createElement("h3", null, "Saved searches"))),
                !isHomepage &&
                    this.state.savedQueries.length === 0 && React.createElement("p", null, "You don't have any saved searches yet."),
                this.state.savedQueries.map((savedQuery, i) => (React.createElement(SavedQuery, { user: this.props.user, key: `${savedQuery.query}-${i}`, savedQuery: savedQuery, onDidDuplicate: this.onDidDuplicateSavedQuery, isLightTheme: this.props.isLightTheme })))),
            this.state.savedQueries.length === 0 &&
                this.state.user &&
                isHomepage && (React.createElement("div", { className: "saved-query" },
                React.createElement(Link, { to: "/search/searches" },
                    React.createElement("div", { className: `saved-query__row` },
                        React.createElement("div", { className: "saved-query-row__add-query" },
                            React.createElement(AddIcon, { className: "icon-inline" }),
                            " Add a new search to start monitoring your code")))))));
    }
}
export class SavedQueriesPage extends SavedQueries {
    componentDidMount() {
        super.componentDidMount();
        eventLogger.logViewEvent('SavedQueries');
    }
}
//# sourceMappingURL=SavedQueries.js.map