import ContentCopyIcon from 'mdi-react/ContentCopyIcon';
import DeleteIcon from 'mdi-react/DeleteIcon';
import PencilIcon from 'mdi-react/PencilIcon';
import * as React from 'react';
import { Subject, Subscription } from 'rxjs';
import { startWith, switchMap, withLatestFrom } from 'rxjs/operators';
import { eventLogger } from '../../tracking/eventLogger';
import { createSavedQuery, deleteSavedQuery } from '../backend';
import { SavedQueryRow } from './SavedQueryRow';
import { SavedQueryUpdateForm } from './SavedQueryUpdateForm';
export class SavedQuery extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = { isEditing: false, isSaving: false, loading: true, refreshedAt: 0, redirect: false };
        this.componentUpdates = new Subject();
        this.refreshRequested = new Subject();
        this.duplicateRequested = new Subject();
        this.deleteRequested = new Subject();
        this.subscriptions = new Subscription();
        this.toggleEditing = (e) => {
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }
            eventLogger.log('SavedQueryToggleEditing', { queries: { editing: !this.state.isEditing } });
            this.setState(state => ({ isEditing: !state.isEditing }));
        };
        this.onDidUpdateSavedQuery = () => {
            eventLogger.log('SavedQueryUpdated');
            this.setState({ isEditing: false, approximateResultCount: undefined, loading: true }, () => {
                this.refreshRequested.next();
                if (this.props.onDidUpdate) {
                    this.props.onDidUpdate();
                }
            });
        };
        this.duplicate = (e) => {
            e.stopPropagation();
            e.preventDefault();
            this.duplicateRequested.next();
        };
        this.confirmDelete = (e) => {
            e.stopPropagation();
            e.preventDefault();
            if (window.confirm('Delete this saved query?')) {
                eventLogger.log('SavedQueryDeleted');
                this.deleteRequested.next();
            }
            else {
                eventLogger.log('SavedQueryDeletedCanceled');
            }
        };
    }
    componentDidMount() {
        const propsChanges = this.componentUpdates.pipe(startWith(this.props));
        this.subscriptions.add(this.duplicateRequested
            .pipe(withLatestFrom(propsChanges), switchMap(([, props]) => createSavedQuery(props.savedQuery.subject, duplicate(props.savedQuery.description), props.savedQuery.query, props.savedQuery.showOnHomepage, props.savedQuery.notify, props.savedQuery.notifySlack)))
            .subscribe(newSavedQuery => {
            if (this.props.onDidDuplicate) {
                this.props.onDidDuplicate();
            }
        }, err => {
            console.error(err);
        }));
        this.subscriptions.add(this.deleteRequested
            .pipe(withLatestFrom(propsChanges), switchMap(([, props]) => deleteSavedQuery(props.savedQuery.subject, props.savedQuery.id)))
            .subscribe(() => {
            if (this.props.onDidDelete) {
                this.props.onDidDelete();
            }
        }, err => {
            console.error(err);
        }));
    }
    componentWillReceiveProps(newProps) {
        this.componentUpdates.next(newProps);
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        return (React.createElement(SavedQueryRow, { query: this.props.savedQuery.query, description: this.props.savedQuery.description, className: this.state.isEditing ? 'editing' : '', eventName: "SavedQueryClick", isLightTheme: this.props.isLightTheme, actions: React.createElement("div", { className: "saved-query-row__actions" },
                !this.state.isEditing && (React.createElement("button", { className: "btn btn-icon action", onClick: this.toggleEditing },
                    React.createElement(PencilIcon, { className: "icon-inline" }),
                    "Edit")),
                !this.state.isEditing && (React.createElement("button", { className: "btn btn-icon action", onClick: this.duplicate },
                    React.createElement(ContentCopyIcon, { className: "icon-inline" }),
                    "Duplicate")),
                React.createElement("button", { className: "btn btn-icon action", onClick: this.confirmDelete },
                    React.createElement(DeleteIcon, { className: "icon-inline" }),
                    "Delete")), form: this.state.isEditing && (React.createElement("div", { className: "saved-query-row__row" },
                React.createElement(SavedQueryUpdateForm, { user: this.props.user, savedQuery: this.props.savedQuery, onDidUpdate: this.onDidUpdateSavedQuery, onDidCancel: this.toggleEditing }))) }));
    }
}
function duplicate(s) {
    const m = s.match(/ \(copy(?: (\d+))?\)$/);
    if (m && m[1]) {
        return `${s.slice(0, m.index)} (copy ${parseInt(m[1], 10) + 1})`;
    }
    if (m) {
        return `${s.slice(0, m.index)} (copy 2)`;
    }
    return `${s} (copy)`;
}
//# sourceMappingURL=SavedQuery.js.map