import React, { Component, Fragment } from 'react'
import Router from 'next/router'
import { connect } from "react-redux";
import { withStyles } from '@material-ui/core/styles';
import setAuthorizationHeader from "../data/setAuthorizationHeader";
import Loader from './../components/templates/loader'
import { userLoggedIn, requestLoginFailure } from "../actions/auth";

import Head from 'next/head'

const styles = theme => ({
    container: {
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
    },

});

class AuthRouter extends Component {

    componentDidMount() {
        let JWT = this.props.JWT;
        if (JWT === null) {
            //free token
            setAuthorizationHeader()
            localStorage.setItem('ttJWT', '')
            this.props.requestLoginFailure('JWT absent')
            Router.push('/Login');
        }
        else {
            localStorage.setItem('ttJWT', JWT)
            //set token to axios headers
            setAuthorizationHeader(JWT)
            var url = localStorage.getItem('loginRedirect')
            if (url === null)
                url = '/Offres'
            Router.push(url);

            this.props.userLoggedIn()
        }

    }

    render() {
        return (
        <Fragment>
            <Head>
                <title key="title">OAuth authentification router</title>
                <meta key="robots" name="robots" content="noindex, nofollow"></meta>
            </Head>
            <div>
                <Loader />
            </div>
        </Fragment>
        )
    }
}

AuthRouter.getInitialProps = function (context) {
    const { JWT } = context.query

    return { JWT: JWT };
}



export default withStyles(styles)(connect(null, { userLoggedIn, requestLoginFailure })(AuthRouter));

