import React, { useRef, useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';

import { authenticationService } from '../_services';

export const PrivateRoute = ({ comp: Component, ...rest }) => {
    const currentUser = useRef(authenticationService.currentUserValue);
    const [expiredAuthCheck, updateExpiredAuthCheck] = useState(0);

    useEffect(() => {
        if (sessionStorage.getItem("currentUser")) {
            toCheckExpiryOfToken();
        }
    }, []);

    async function toCheckExpiryOfToken() {
        // check the expiry of token
        try {
            const jwt = JSON.parse(sessionStorage.getItem("currentUser")).jwtToken;
            const payloadJwt = jwt.split(".")[1];
            const decodedString = JSON.parse(Buffer.from(payloadJwt, 'base64'));
            const expiryDateOfToken = new Date(decodedString.exp * 1000);
            console.log(decodedString.exp*1000 - 600, Date.now());
            if (Date.now() > (decodedString.exp - 600)) {
                const res = await authenticationService.refreshFireToken();
                if (res) updateExpiredAuthCheck(1);
            }
        } catch (error) {
            console.log("Bad Payload");
            updateExpiredAuthCheck(-1);
        }
    }

    if (!currentUser.current) {
        // not logged in so redirect to login page with the return url
        return <Redirect to={{ pathname: '/login', state: { from: rest.location } }} />
    }

    if (expiredAuthCheck === -1) {
        return <Redirect to={{ pathname: '/login', state: { from: rest.location } }} />
    }

    if (expiredAuthCheck === 0) {
        return <div className='center-flex mt-3-0'>
            Getting you permission to enter the class...
        </div>
    }

    return <Route {...rest}
        render={props => {
            // const currentUser = authenticationService.currentUserValue;
            // if (!currentUser) {
            //     // not logged in so redirect to login page with the return url
            //     return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            // }

            // authorised so return component
            return <Component {...props} mathJax={rest.mathJax} location={props.location} />
        }} />
}