import React from 'react';
import {withNamespaces} from "react-i18next";
import {
    Redirect
} from 'react-router-dom';
import {ApiRequest, POST} from '../../lib/ApiRequest';
import provideAuth, {logout} from '../../lib/Auth';
import {injectSheet} from "../../lib/theme";
import {Button} from '../../component/Form';
import PasswordReset from './PasswordReset';
import {bindForm} from "../FormApi";
import StyleGrid from "../../lib/StyleGrid";
import i18n from "../../lib/i18n";

const styling = theme => ({
    wrapper: {
        margin: '0 auto',
        [StyleGrid.smUp]: {
            width: '280px'
        }
    },
    btn: {
        textAlign: 'center',
        marginTop: theme.gutter.base * 4 + 'px'
    },
    reset: {
        marginTop: theme.gutter.base * 4 + 'px'
    }
});

class Login extends React.Component {

    constructor(props) {
        super(props);

        // binding internal sender through `connect`
        props.connect.sender(this.sender.bind(this));
    }

    sender(evt, data, touched, props) {
        // modify submit values before sending to server
        return (new ApiRequest('auth', POST, 'verify', data))
            .debug(true)
            .header({})
            .exec()
            .then((res) => {
                if(res && res.data) {
                    if(res.data.token) {
                        props.auth.addToken(res.data.token);
                        (new ApiRequest('auth', POST, 'check-allowed', data))
                            .debug(true)
                            .header({})
                            .exec()
                            .then((res) => {
                                if(res && res.data) {
                                } else {
                                }
                            });
                    }
                    if(res.data.error) {
                        // todo: optimize error message after it is developed in FormApi
                        throw new Error('auth-failed');
                    }
                    /*this.setState({
                        //last_id: res.data.created
                    });*/
                } else {

                }
            });
    }

    render() {
        const {t, FormApi, InputGroupText, classes, theme} = this.props;

        return (
            this.props.auth.is ? (
                    'sended' === this.props.process ?
                        /* Just logged in */
                        <Redirect to={'/' + i18n.languages[0] + '/dashboard'}/> :
                        /* Logged in but not after a state-change */
                        <p>{t('login.already')}<br/><Button onClick={logout}>Logout</Button></p>
                ) :
                <div className={classes.wrapper}>
                    <FormApi>
                        <h3>{t('login.name')}</h3>
                        <InputGroupText style={{wrapper:{margin: theme.gutter.base * 4 + 'px 0'}}} name='username' lbl={t('username')} required/>
                        <InputGroupText style={{wrapper:{margin: theme.gutter.base * 4 + 'px 0'}}} name='password' type='password' lbl={t('pass')} required/>

                        {this.props.process && 'received' !== this.props.process ? <p>{t('process-' + this.props.process)}</p> : null}
                        <Button style={styling(theme).btn}>{t('login.submit')}</Button>
                    </FormApi>
                    <PasswordReset style={styling(theme).reset}/>
                </div>
        );
    }
}

export default provideAuth(withNamespaces(['page--auth'])(bindForm(injectSheet(styling)(Login))));
