import React, { useEffect, useState } from 'react';
import { withRouter } from "react-router-dom";
import { compose } from "redux";
import { connect } from "react-redux";
import LoadingComponent from '@/common/Loading'


function Loading(props) {

    const [isLoading, setLoadingState] = useState(true)

    useEffect(() => {
        let {user, location, history} = props

        if (history.action === 'POP') {
            history.goBack();
            return
        }

        if (!user.isFetching) {
            if (user.hasError) {
                history.push('/passport', {from: location})
                setLoadingState(false)
            } else {
                if (Object.values(user.data).every(item => !!item).length !== 0) {
                    history.push(location.pathname)
                    setLoadingState(false)
                }
            }
        }
    })

    return (
        <div className={'loading-route'}>
            <LoadingComponent isLoading={isLoading}/>
        </div>
    );
}

export default compose(
    connect(
        state => ({user: state.user}),
        null
    ),
    withRouter
)(Loading)