var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import React from 'react';
import { View, Alert } from 'react-native';
import LoginForm from './LoginForm';
import { Colors, CrossButton, CrossLabel } from 'react-native-cross-components';
import { CognitoUserInputContext } from '../../contexts';
import { OnLogin } from '../../events/OnLogin';
import _ from 'lodash';
import RegisterForm from '../../register/components/RegisterForm';
import { ForgotForm } from '../../forgot/components/ForgotForm';
import { ConfirmForm } from '../../confirm/components/ConfirmForm';
import { OnRegister } from '../../events/OnRegister';
import styles from '../../styles';
import OnConfirmMfaCode from '../../events/OnConfirmMfaCode';
import OnConfirmAccount from '../../events/OnConfirmAccount';
import OnResendSignup from '../../events/OnResendSignup';
/**
 * A form for logging in to AWS Cognito through Amplify.
 *
 * On successful login the {@link ICognitoLoginProps.onLoggedIn} event is triggered.
 *
 * Remarks:
 * * Requires Amplify to be configured:
 *
 * https://aws-amplify.github.io/docs/js/start?ref=amplify-rn-btn&platform=react-native#step-4-integrate-aws-resources
 *
 * Props are {@link ICognitoLoginProps}
 *
 * @example
 *  <CognitoLogin
 *    onLoggedIn={(user) => console.log(user)}
 *     loginButtonProps={{title: 'Engage'}}>
 *     <Text>Custom layouts here</Text>
 *  </CognitoLogin>
 */
export class CognitoLogin extends React.Component {
    constructor(props) {
        super(props);
        this.onResultChanged = () => {
            let form = 'Login';
            const result = this.state.result;
            const authState = _.get(this.state, ['result', 'state']);
            if (!authState) {
                return;
            }
            switch (authState) {
                case 'Authenticated':
                    form = 'Login';
                    if (result && result.user && this.props.onLoggedIn) {
                        this.props.onLoggedIn(result.user);
                    }
                    break;
                case 'ConfirmAccountCodeWaiting':
                    form = 'ConfirmAccount';
                    break;
                case 'ConfirmLoginMFAWaiting':
                    form = 'ConfirmMFALogin';
                    break;
                default:
                    break;
            }
            let { message } = this.state;
            if (authState === 'Authenticated') {
                message = 'Logged in!';
            }
            this.setState({ formState: form, message });
        };
        this.onEmailChanged = (email) => {
            const { userInput } = this.state;
            if (_.isNil(email)) {
                return;
            }
            userInput.email = email;
            this.setState({ userInput });
        };
        this.onPasswordChanged = (password) => {
            const { userInput } = this.state;
            if (_.isNil(password)) {
                return;
            }
            userInput.password = password;
            this.setState({ userInput });
        };
        this.onPhoneChanged = (phone) => {
            const { userInput } = this.state;
            let newPhone = phone;
            if (_.isNil(newPhone)) {
                return;
            }
            newPhone = newPhone.replace(' ', '').trim();
            if (!newPhone.startsWith('+')) {
                newPhone = '+' + newPhone;
            }
            userInput.phone = newPhone;
            this.setState({ userInput });
        };
        this.OnResendSignup = () => {
            const { email } = this.state.userInput;
            if (_.isNil(email)) {
                this.setState({ message: 'Please enter username' });
                return;
            }
            const sendButton = {
                text: 'OK',
                onPress: () => OnResendSignup(email),
            };
            Alert.alert('Confirm', 'Re-send code?', [sendButton], { cancelable: true });
        };
        this.onRegister = () => __awaiter(this, void 0, void 0, function* () {
            if (__DEV__)
                console.log('***** onRegister ***** ');
            const result = yield OnRegister(this.state.userInput);
            if (__DEV__)
                console.log('**** onRegister result: ', result);
            this.setState({ result }, this.onResultChanged);
        });
        this.onConfirmAccount = () => __awaiter(this, void 0, void 0, function* () {
            if (_.isNil(this.state.code) ||
                this.state.code === '' ||
                _.isNil(this.state.userInput.email)) {
                this.setState({ message: 'Need code and user e-mail' });
                return;
            }
            if (__DEV__)
                console.log('***** onConfirmAccount ***** ');
            const result = yield OnConfirmAccount(this.state.code, this.state.userInput.email);
            if (__DEV__)
                console.log('**** onConfirmAccount result: ', result);
            this.setState({ result, formState: 'Login' }, this.onResultChanged);
        });
        this.onConfirmMFACode = () => __awaiter(this, void 0, void 0, function* () {
            if (_.isNil(this.state.code) ||
                this.state.code === '' ||
                _.isNil(this.state.userInput.email)) {
                return;
            }
            if (__DEV__)
                console.log('***** onConfirmMFACode ***** ');
            const result = yield OnConfirmMfaCode(this.state.code, this.state.userInput.email);
            if (__DEV__)
                console.log('**** onConfirmMFACode result: ', result);
            this.setState({ result }, this.onResultChanged);
        });
        this.onLogin = () => __awaiter(this, void 0, void 0, function* () {
            if (__DEV__)
                console.log('***** onLogin ***** ');
            const result = yield OnLogin(this.state.userInput);
            if (__DEV__)
                console.log('**** onLogin result: ', result);
            this.setState({ result }, this.onResultChanged);
        });
        this.state = {
            result: undefined,
            userInput: __DEV__
                ? {
                    email: 'cogtest@mailinator.com',
                    password: 'Password1#',
                    phone: '+46730555252',
                }
                : { email: undefined, password: undefined },
            formState: 'Login',
            code: undefined,
            message: undefined,
        };
        this.onEmailChanged = this.onEmailChanged.bind(this);
        this.onPasswordChanged = this.onPasswordChanged.bind(this);
        this.onPhoneChanged = this.onPhoneChanged.bind(this);
        this.onConfirmMFACode = this.onConfirmMFACode.bind(this);
        this.onConfirmAccount = this.onConfirmAccount.bind(this);
        this.onLogin = this.onLogin.bind(this);
        this.onResultChanged = this.onResultChanged.bind(this);
        this.OnResendSignup = this.OnResendSignup.bind(this);
    }
    render() {
        // Extract error message. Could be an Error or a string
        const error = _.get(this.state, ['result', 'error', 'message']) ||
            _.get(this.state, ['result', 'error'] || this.state.message);
        return (React.createElement(View, { style: styles.container },
            this.props.children,
            this.state.formState === 'Login' ? (React.createElement(View, { style: styles.container },
                React.createElement(LoginForm, Object.assign({ initialEmail: this.state.userInput.email, initialPassword: this.state.userInput.password, onEmailChanged: this.onEmailChanged, onPasswordChanged: this.onPasswordChanged }, this.props)),
                React.createElement(CrossButton, Object.assign({ style: styles.marginTop10, buttonStyle: styles.buttonStyle, onPress: () => __awaiter(this, void 0, void 0, function* () { return yield this.onLogin(); }), mode: 'contained', title: 'Log in', backgroundColor: Colors.NextButton, iconName: 'sign-in' }, this.props.loginButtonProps)),
                React.createElement(CrossButton, Object.assign({ style: styles.marginTop10, buttonStyle: styles.buttonStyle, onPress: () => this.setState({
                        formState: 'Register',
                    }), mode: 'contained', title: 'Register', backgroundColor: Colors.BackButton }, this.props.registerButtonProps)))) : null,
            this.state.formState === 'Register' ? (React.createElement(View, { style: styles.container },
                React.createElement(RegisterForm, Object.assign({ initialPhone: this.state.userInput.phone, onPhoneChanged: this.onPhoneChanged, initialEmail: this.state.userInput.email, initialPassword: this.state.userInput.password, onEmailChanged: this.onEmailChanged, onPasswordChanged: this.onPasswordChanged }, this.props)),
                React.createElement(CrossButton, Object.assign({ style: styles.marginTop10, buttonStyle: styles.buttonStyle, onPress: () => __awaiter(this, void 0, void 0, function* () { return yield this.onRegister(); }), mode: 'contained', title: 'Save', backgroundColor: Colors.NextButton, iconName: 'sign-in' }, this.props.saveButtonProps)),
                React.createElement(CrossButton, Object.assign({ style: styles.marginTop10, buttonStyle: styles.buttonStyle, onPress: () => this.setState({
                        formState: 'Login',
                    }), mode: 'contained', title: 'Cancel', backgroundColor: Colors.CancelButton }, this.props.cancelButtonProps)))) : null,
            this.state.formState === 'Forgot' ? (React.createElement(ForgotForm, Object.assign({}, this.props))) : null,
            this.state.formState === 'ConfirmAccount' ? (React.createElement(View, { style: styles.container },
                React.createElement(ConfirmForm, Object.assign({ testID: 'ConfirmAccountForm', code: this.state.code, initialEmail: this.state.userInput.email, onEmailChanged: this.onEmailChanged, onConfirmPress: () => __awaiter(this, void 0, void 0, function* () { return yield this.onConfirmAccount(); }), onCodeChanged: (code) => this.setState({ code }) }, this.props)),
                React.createElement(CrossButton, Object.assign({ style: styles.marginTop10, buttonStyle: styles.buttonStyle, onPress: () => this.OnResendSignup(), mode: 'contained', title: 'Resend code', backgroundColor: Colors.CancelButton }, this.props.cancelButtonProps)))) : null,
            this.state.formState === 'ConfirmMFALogin' ? (React.createElement(ConfirmForm, { testID: 'ConfirmMFAForm', code: this.state.code, initialEmail: this.state.userInput.email, onEmailChanged: this.onEmailChanged, onConfirmPress: () => __awaiter(this, void 0, void 0, function* () { return yield this.onConfirmMFACode(); }), onCodeChanged: (code) => this.setState({ code }) })) : null,
            React.createElement(CognitoUserInputContext.Provider, { value: this.state.userInput }),
            React.createElement(CrossLabel, { isCaption: true, style: { color: 'red' } }, (error || '').toString())));
    }
}
export default CognitoLogin;
//# sourceMappingURL=CognitoLogin.js.map