import { LicenseManager } from 'ag-grid-enterprise';
import axios from 'axios';
import { observer } from 'mobx-react';
import React from 'react';
import { BrowserRouter as Router, Redirect, Route, Switch, useHistory, useLocation } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import { SWRConfig } from 'swr';
import { Chargement } from './components/Commun/Chargement';
import { Erreur } from './components/Commun/Erreur';
import { Login } from './components/Commun/Login';
import EntetePage from './components/EntetePage/EntetePage';
import GestionDecisionBarreNavParamsActions from './components/EnteteVues/GestionDecisionBarreNavParamsActions';
import GestionDecision from './components/GestionDecision/GestionDecision';
import GestionITD from './components/GestionPerimetre/GestionITD';
import GestionPerimetre from './components/GestionPerimetre/GestionPerimetre';
// import Indicateurs from './components/Indicateurs/Indicateurs';
import { NAVIGATION, PROFILS } from './constantes/constantes';
import AppConfigStore, { AppConfigContext } from './stores/AppConfigStore';

//TODO faut-il stocker la license dans un fichier de propriétés modifiable en dehors du code compilé ?
LicenseManager.setLicenseKey(
    'CompanyName=SMLB-NEXT_on_behalf_of_DIR DES RESS. HUMAINES DE LEMAA,LicensedApplication=OGURE NG,LicenseType=SingleApplication,LicensedConcurrentDeveloperCount=1,LicensedProductionInstancesCount=1,AssetReference=AG-019349,ExpiryDate=24_September_2022_[v2]_MTY2Mzk3NDAwMDAwMA==7903ffcc2e2649261b5331bada95402c'
);

let appConfig = new AppConfigStore();

/**
 * Composant racine de l'application Ogure NG.
 *
 * @component
 */
const App = observer(() => {
    // const routeWithoutSousVivier = NAVIGATION.INDICATEURS
    const routeWithoutDroit = '/'
    const hasSousVivier = appConfig.sousViviersUtilisateurConnecte?.length;
    const isSuper = !appConfig.profilSelectionne && appConfig.hasProfil(PROFILS.SUPER);

    return appConfig.ready ? (
            !appConfig.error ? (
                appConfig.utilisateurConnecte ? (
                    <SWRConfig
                        value={{
                            refreshInterval: 10000,
                            fetcher: (url) =>
                                axios(url).then((res) => {
                                    // console.log('swr res', res);
                                    return res?.data;
                                })
                        }}
                    >
                        <AppConfigContext.Provider value={appConfig}>
                            <Router basename={''}>
                                <div className="App container-fluid p-0 d-flex flex-column align-items-stretch">
                                    <EntetePage />

                                    <GestionDecisionBarreNavParamsActions />

                                    <div className="corpsDePage d-flex flex-column align-items-stretch" role="main">
                                        <Switch>
                                            <Route exact path="/" render={
                                                () => <Redirect to={appConfig.profilSelectionne == PROFILS.ITD 
                                                        ? '/GestionITD'
                                                        : [PROFILS.PCP, PROFILS.FILIERE, PROFILS.BVT].includes(appConfig.profilSelectionne)
                                                        ? NAVIGATION.PERIMETRE 
                                                        : routeWithoutDroit} />
                                            } />
                                            <Route path={NAVIGATION.PERIMETRE} render={
                                                () => [PROFILS.PCP, PROFILS.FILIERE, PROFILS.BVT].includes(appConfig.profilSelectionne)
                                                        ? <GestionPerimetre />
                                                        : <Redirect to={routeWithoutDroit} />
                                            } />
                                            <Route path="/GestionITD" render={
                                                () => [PROFILS.ITD, PROFILS.FILIERE, PROFILS.PCP].includes(appConfig.profilSelectionne)
                                                        ? <GestionITD />
                                                        : <Redirect to={routeWithoutDroit} />
                                            } />
                                            <Route path={NAVIGATION.GESTION_DECISIONS} render={
                                                () => appConfig.profilSelectionne == PROFILS.FILIERE 
                                                ? <GestionDecision />
                                                : <Redirect to={routeWithoutDroit} />
                                                // () => !isSuper && !appConfig.profilSelectionne
                                                //         ? <Redirect to={routeWithoutDroit} />
                                                //         : hasSousVivier ? <GestionDecision /> : <Redirect to={routeWithoutSousVivier} />
                                            } />
                                            <Route path={NAVIGATION.INDICATEURS} render={
                                                () => <Redirect to={routeWithoutDroit} />
                                            } />
                                            {/* <Route path={routeWithoutSousVivier}>
                                                <Indicateurs />
                                            </Route> */}
                                        </Switch>
                                    </div>
                                </div>
                            </Router>
                        </AppConfigContext.Provider>
                        <ToastContainer
                            position="bottom-right"
                            autoClose={5000}
                            hideProgressBar={false}
                            newestOnTop
                            closeOnClick
                            rtl={false}
                            draggable
                            pauseOnHover
                        />
                    </SWRConfig>
                ) : (
                    <Login />
                )
            ) : (
                <Erreur />
            )
        ) : (
            <div className={'vh-100'}>
                <Chargement />
                <ToastContainer
                    position="bottom-right"
                    autoClose={5000}
                    hideProgressBar={false}
                    newestOnTop
                    closeOnClick
                    rtl={false}
                    draggable
                    pauseOnHover
                />{' '}
            </div>
        )
});

export default App;

/*
  ------------------------------------------------------------------------------------------------------------------------
  Base d'authentification + routage. Cf. https://reactrouter.com/web/example/auth-workflow
  ------------------------------------------------------------------------------------------------------------------------
*/

// A wrapper for <Route> that redirects to the login
// screen if you're not yet authenticated.
function PrivateRoute({ children, ...rest }) {
    let auth = useAuth();
    return (
        <Route
            {...rest}
            render={({ location }) =>
                auth.user ? (
                    children
                ) : (
                    <Redirect
                        to={{
                            pathname: '/connexion',
                            state: { from: location }
                        }}
                    />
                )
            }
        />
    );
}

/**
 * Ecran de connexion
 * @returns Elément REACT de l'écran de connexion
 */
function EcranConnexion() {
    let history = useHistory();
    let location = useLocation();
    let auth = useAuth();

    let { from } = location.state || { from: { pathname: '/' } };

    let login = (e) => {
        e.preventDefault();
        auth.signin(() => {
            history.replace(from);
        });
    };

    return (
        <div className="container">
            <p>
                Vous devez{' '}
                <a href="#" onClick={login}>
                    vous connecter
                </a>{' '}
                pour accéder à l'écran {from.pathname}
            </p>
        </div>
    );
}
