import { LoadingSpinner } from '@sourcegraph/react-loading-spinner';
import { upperFirst } from 'lodash';
import UserIcon from 'mdi-react/UserIcon';
import * as React from 'react';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router-dom';
import { from, Subscription } from 'rxjs';
import { Form } from '../components/Form';
import { HeroPage } from '../components/HeroPage';
import { PageTitle } from '../components/PageTitle';
import { eventLogger } from '../tracking/eventLogger';
import { asError } from '../util/errors';
import { signupTerms } from '../util/features';
import { EmailInput, getReturnTo, PasswordInput, UsernameInput } from './SignInSignUpCommon';
export class SignUpForm extends React.Component {
    constructor(props) {
        super(props);
        this.subscriptions = new Subscription();
        this.onEmailFieldChange = (e) => {
            this.setState({ email: e.target.value });
        };
        this.onUsernameFieldChange = (e) => {
            this.setState({ username: e.target.value });
        };
        this.onPasswordFieldChange = (e) => {
            this.setState({ password: e.target.value });
        };
        this.handleSubmit = (event) => {
            event.preventDefault();
            if (this.state.loading) {
                return;
            }
            this.setState({ loading: true });
            this.subscriptions.add(from(this.props
                .doSignUp({
                email: this.state.email,
                username: this.state.username,
                password: this.state.password,
            })
                .catch(error => this.setState({ error: asError(error), loading: false }))).subscribe());
            eventLogger.log('InitiateSignUp', {
                signup: {
                    user_info: {
                        signup_email: this.state.email,
                        signup_username: this.state.username,
                    },
                },
            });
        };
        this.state = {
            email: '',
            username: '',
            password: '',
            loading: false,
        };
    }
    render() {
        return (React.createElement(Form, { className: "signin-signup-form signup-form", onSubmit: this.handleSubmit },
            this.state.error && (React.createElement("div", { className: "alert alert-danger my-2" },
                "Error: ",
                upperFirst(this.state.error.message))),
            React.createElement("div", { className: "form-group" },
                React.createElement(EmailInput, { className: "signin-signup-form__input", onChange: this.onEmailFieldChange, required: true, value: this.state.email, disabled: this.state.loading, autoFocus: true })),
            React.createElement("div", { className: "form-group" },
                React.createElement(UsernameInput, { className: "signin-signup-form__input", onChange: this.onUsernameFieldChange, value: this.state.username, required: true, disabled: this.state.loading })),
            React.createElement("div", { className: "form-group" },
                React.createElement(PasswordInput, { className: "signin-signup-form__input", onChange: this.onPasswordFieldChange, value: this.state.password, required: true, disabled: this.state.loading, autoComplete: "new-password" })),
            React.createElement("div", { className: "form-group" },
                React.createElement("button", { className: "btn btn-primary btn-block", type: "submit", disabled: this.state.loading }, this.state.loading ? (React.createElement(LoadingSpinner, { className: "icon-inline" })) : (this.props.buttonLabel || 'Sign up'))),
            signupTerms && (React.createElement("small", { className: "form-text text-muted" },
                "By signing up, you agree to our",
                ' ',
                React.createElement("a", { href: "https://about.sourcegraph.com/terms", target: "_blank" }, "Terms of Service"),
                ' ',
                "and",
                ' ',
                React.createElement("a", { href: "https://about.sourcegraph.com/privacy", target: "_blank" }, "Privacy Policy"),
                "."))));
    }
}
export class SignUpPage extends React.Component {
    constructor() {
        super(...arguments);
        this.doSignUp = (args) => fetch('/-/sign-up', {
            credentials: 'same-origin',
            method: 'POST',
            headers: Object.assign({}, window.context.xhrHeaders, { Accept: 'application/json', 'Content-Type': 'application/json' }),
            body: JSON.stringify(args),
        }).then(resp => {
            if (resp.status !== 200) {
                return resp.text().then(text => Promise.reject(new Error(text)));
            }
            window.location.replace(getReturnTo(this.props.location));
            return Promise.resolve();
        });
    }
    componentDidMount() {
        eventLogger.logViewEvent('SignUp', {}, false);
    }
    render() {
        if (this.props.user) {
            const returnTo = getReturnTo(this.props.location);
            return React.createElement(Redirect, { to: returnTo });
        }
        if (!window.context.allowSignup) {
            return React.createElement(Redirect, { to: "/sign-in" });
        }
        return (React.createElement("div", { className: "signin-signup-page sign-up-page" },
            React.createElement(PageTitle, { title: "Sign up" }),
            React.createElement(HeroPage, { icon: UserIcon, title: "Sign up for Sourcegraph", cta: React.createElement("div", null,
                    React.createElement(Link, { className: "signin-signup-form__mode", to: `/sign-in?${this.props.location.search}` }, "Already have an account? Sign in."),
                    React.createElement(SignUpForm, Object.assign({}, this.props, { doSignUp: this.doSignUp }))) })));
    }
}
//# sourceMappingURL=SignUpPage.js.map