import { ApplicationContainer } from 'arm-core-layouts';
import { Routing } from 'arm-router';
import React, { PureComponent, useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Prompt, Route, Switch, useHistory } from 'react-router-dom';

import AccountActions from './account/AccountActions.js';
import { getMasterPageMenuInfo } from './MasterPage.jsx';


export default class Standalone extends PureComponent {
    state = { to: '' }

    componentDidMount() {
        this.initStandalone();
        AccountActions.getSession().then(this.checkIsLogged);
    }

    initStandalone() {
        const { history } = this.props; //route props
        this.setState(() => ({ to: this.getBasePath() }));
        history.push('/standalone');
    }
    
    getBasePath(){
        const { pathname } = this.props.location; //route props
        const crumbs = pathname.split('/');
        crumbs.splice(0, 1); //rimuovo lo spazio creato dal primo slash

        if (pathname.includes('pk')){
            return `/${crumbs[0]}/${crumbs[1]}/${crumbs[2]}/${crumbs[3]}/${crumbs[4]}`;
        }
        
        return `/${crumbs[0]}/${crumbs[1]}`;
    }

    checkIsLogged = (utente) => {
        const {
            history, match, //route props
            postLogin //dispatch functions
        } = this.props;
        const { path } = match;
        const { to } = this.state;
        if (!utente) history.push(`${path}/login`);
        else {
            postLogin(utente).then(() => history.push(to));
        }
    }

    getPaths() {
        const { utente } = this.props;

        if (!utente) return null;

        return <Routing routesInfo={getMasterPageMenuInfo()}/>
    }

    render() {
        const { utente, opzioni } = this.props;
        const { path } = this.props.match;
        const { to, section } = this.state;

        return (
            <>
                <ApplicationContainer>
                    <Switch>
                        <Route path={`${path}/login`} render={(props) => <Login {...props} to={to} />} />
                        {this.getPaths()}
                        {utente && <Route component={NotFound} />}
                    </Switch>
                </ApplicationContainer>
                <PromptStandalone />
            </>
        );
    }
}

const mapStateToProps = (state) => ({
    utente: state.account.utente,
    opzioni: state.app.opzioni
});

const mapDispatchToProps = (dispatch) => ({
    postLogin: (resolve) => dispatch(AccountActions.postLogin(resolve))
});

Standalone = connect(mapStateToProps, mapDispatchToProps)(Standalone);

function PromptStandalone(){
    const history = useHistory();

    const [ nextLocation, setNextLocation ] = useState('');

    useEffect(() => {
        if (nextLocation) history.push(nextLocation);
        if (nextLocation !== '') setNextLocation('');
    }, [nextLocation]);

    const checkIsInStandalone = useCallback((location) => {
        const pathname = location.pathname;
        if (pathname.includes('standalone')) return true;

        const newLocation = `/standalone${pathname}`;
        console.log('[PromptStandalone]: converting location', location, 'to', newLocation);
        setNextLocation(newLocation);

        return false;
    }, [history]);

    return <Prompt when={true} message={checkIsInStandalone} />
}