import DeleteIcon from 'mdi-react/DeleteIcon';
import * as React from 'react';
import { Subject, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { gql, mutateGraphQL, queryGraphQL } from '../../backend/graphql';
import { FilteredConnection } from '../../components/FilteredConnection';
import { PageTitle } from '../../components/PageTitle';
import { siteFlags } from '../../site/backend';
import { eventLogger } from '../../tracking/eventLogger';
import { createAggregateError } from '../../util/errors';
import { AddUserEmailForm } from './AddUserEmailForm';
import { setUserEmailVerified } from './backend';
class UserEmailNode extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = {
            loading: false,
        };
        this.remove = () => {
            if (!window.confirm(`Remove the email address ${this.props.node.email}?`)) {
                return;
            }
            this.setState({
                errorDescription: undefined,
                loading: true,
            });
            mutateGraphQL(gql `
                mutation RemoveUserEmail($user: ID!, $email: String!) {
                    removeUserEmail(user: $user, email: $email) {
                        alwaysNil
                    }
                }
            `, { user: this.props.user.id, email: this.props.node.email })
                .pipe(map(({ data, errors }) => {
                if (!data || (errors && errors.length > 0)) {
                    throw createAggregateError(errors);
                }
            }))
                .subscribe(() => {
                this.setState({ loading: false });
                eventLogger.log('UserEmailAddressDeleted');
                if (this.props.onDidUpdate) {
                    this.props.onDidUpdate();
                }
            }, error => this.setState({ loading: false, errorDescription: error.message }));
        };
        this.setAsVerified = () => this.setVerified(true);
        this.setAsUnverified = () => this.setVerified(false);
    }
    render() {
        let statusFragment;
        if (this.props.node.verified) {
            statusFragment = React.createElement("span", { className: "badge badge-success" }, "Verified");
        }
        else if (this.props.node.verificationPending) {
            statusFragment = React.createElement("span", { className: "badge badge-info" }, "Verification pending");
        }
        else {
            statusFragment = React.createElement("span", { className: "badge badge-secondary" }, "Not verified");
        }
        return (React.createElement("li", { className: "list-group-item py-2" },
            React.createElement("div", { className: "d-flex align-items-center justify-content-between" },
                React.createElement("div", null,
                    React.createElement("strong", null, this.props.node.email),
                    " \u00A0",
                    statusFragment),
                React.createElement("div", null,
                    React.createElement("button", { className: "btn btn-sm btn-danger", onClick: this.remove, disabled: this.state.loading, "data-tooltip": "Remove email address" },
                        React.createElement(DeleteIcon, { className: "icon-inline" })),
                    ' ',
                    this.props.node.viewerCanManuallyVerify && (React.createElement("button", { className: "btn btn-sm btn-secondary", onClick: this.props.node.verified ? this.setAsUnverified : this.setAsVerified, disabled: this.state.loading }, this.props.node.verified ? 'Mark as unverified' : 'Mark as verified')))),
            this.state.errorDescription && (React.createElement("div", { className: "alert alert-danger mt-2" }, this.state.errorDescription))));
    }
    setVerified(verified) {
        this.setState({
            errorDescription: undefined,
            loading: true,
        });
        setUserEmailVerified(this.props.user.id, this.props.node.email, verified).subscribe(() => {
            this.setState({ loading: false });
            if (verified) {
                eventLogger.log('UserEmailAddressMarkedVerified');
            }
            else {
                eventLogger.log('UserEmailAddressMarkedUnverified');
            }
            if (this.props.onDidUpdate) {
                this.props.onDidUpdate();
            }
        }, error => this.setState({ loading: false, errorDescription: error.message }));
    }
}
export class UserAccountEmailsPage extends React.Component {
    constructor() {
        super(...arguments);
        this.state = {};
        this.userEmailUpdates = new Subject();
        this.subscriptions = new Subscription();
        this.queryUserEmails = (args) => queryGraphQL(gql `
                query UserEmails($user: ID!) {
                    node(id: $user) {
                        ... on User {
                            emails {
                                email
                                verified
                                verificationPending
                                viewerCanManuallyVerify
                            }
                        }
                    }
                }
            `, { user: this.props.user.id }).pipe(map(({ data, errors }) => {
            if (!data || !data.node) {
                throw createAggregateError(errors);
            }
            const user = data.node;
            if (!user.emails) {
                throw createAggregateError(errors);
            }
            return {
                nodes: user.emails,
                totalCount: user.emails.length,
            };
        }));
        this.onDidUpdateUserEmail = () => this.userEmailUpdates.next();
    }
    componentDidMount() {
        eventLogger.logViewEvent('UserAccountEmails');
        this.subscriptions.add(siteFlags.subscribe(siteFlags => this.setState({ siteFlags })));
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        const nodeProps = {
            user: this.props.user,
            onDidUpdate: this.onDidUpdateUserEmail,
        };
        return (React.createElement("div", { className: "user-settings-emails-page" },
            React.createElement(PageTitle, { title: "Emails" }),
            React.createElement("h2", null, "Emails"),
            this.state.siteFlags &&
                !this.state.siteFlags.sendsEmailVerificationEmails && (React.createElement("div", { className: "alert alert-warning mt-2" }, "Sourcegraph is not configured to send email verifications. Newly added email addresses must be manually verified by a site admin.")),
            React.createElement(FilteredConnection, { className: "list-group list-group-flush mt-3", noun: "email address", pluralNoun: "email addresses", queryConnection: this.queryUserEmails, nodeComponent: UserEmailNode, nodeComponentProps: nodeProps, updates: this.userEmailUpdates, hideSearch: true, noSummaryIfAllNodesVisible: true, history: this.props.history, location: this.props.location }),
            React.createElement(AddUserEmailForm, { className: "mt-4", user: this.props.user.id, onDidAdd: this.onDidUpdateUserEmail })));
    }
}
//# sourceMappingURL=UserAccountEmailsPage.js.map