import React, { useState, useEffect, useContext, useRef } from 'react';

import { Route, Switch } from 'react-router-dom';

import { Skeleton } from 'antd';

import { GlobalHeader, ChangePassword } from 'soxo-firebase-core';

// import MenuTemplate from 'soxo-firebase-core';

import './landing-api.scss';

import { GlobalContext, ModuleRoutes, Profile, SpotlightSearch, SettingsUtil } from 'soxo-firebase-core';

import HomePageAPI from './../../pages/homepage-api/homepage-api';

import MenuTemplate from './../menu-template-api/menu-template-api';

import ReportingDashboard from '../../modules/reporting/components/reporting-dashboard/reporting-dashboard';

import {
    MenusAPI,
    CoreScripts,
    UsersAPI
}
    from '../../../core/models';
/**
 * Landing file for
 *
 * @param {*} props
 * @returns
 */
export default function Landing({ history, CustomComponents, appSettings, ...props }) {

    const [loader, setLoader] = useState(false);

    const [modules, setModules] = useState([]);

    const [connected, setConnected] = useState();

    const { user = {}, selectedBranch } = useContext(GlobalContext);

    const [meta, setMeta] = useState({});

    const [reports, setReports] = useState([]);

    var config = {};

    if (user.role && user.role.name) {

        var role = user.role.name.toLowerCase();
    }

    // Variable decides the control of homepage
    // #TODO This is a temporary fix - Homemage 

    let disableHomepage = false;

    if (process.env.REACT_APP_DISABLEHOMEPAGE) {

        disableHomepage = JSON.parse(process.env.REACT_APP_DISABLEHOMEPAGE);
    }

    // useEffect(() => {

    //     // Initialize the menus for the logged in user
    //     initializeUserMenus();

    // }, [selectedBranch]);

    useEffect(() => {

        // Initialize the menus for the logged in user
        initializeUserMenus();

    }, []);

    /**
     * Initialize the user menus
     */
    function initializeUserMenus() {

        loadMenus();

        // need to find what implement, with a login who has the respective value ("wug_custreportids")
        loadScripts(user);
    }


    const keyMap = {
        moveUp: 'Shift+B',
        spotlight: 'Shift+F'
    }

    /**
     * 
     * 
     */
    const loadMenus = async () => {

        setLoader(true);

        const result = await MenusAPI.getMenus(user);

        // console.log(result);

        if (result && Array.isArray(result.result) && result.result.length) {

            setModules(result.result);



        }

        setLoader(false);
    }

    /**
     * 
     */

    /**
     * Function load the definitions of the core script
     * to be show the menu in the left and to decide which is active
     * 
     * @todo We have to change how menus are loaded for reports . If its loaded by user
     * group this can be considered to be included in either the profile api 
     * or the intial bootstrap api which includes loading some configuration
     * 
     * @param {*} user 
     */
    const loadScripts = async (user) => {

        if (user.user_group && user.user_group.wug_custreportids && user.user_group.wug_custreportids !== '') {

            // Saving the report ids to a variable
            let wug_custreportids = user.user_group.wug_custreportids;

            var report_ids = wug_custreportids.split(',');

            const reports = await Promise.all(report_ids.map((id) => CoreScripts.getReportMenu({ id })))

            let filtered = reports.filter((record) => record.active === 'Y').map((result) => {

                return {
                    ...result,
                };

            })

            setReports(filtered);
        }
    }

    // let core_modules = [];

    // Reports length
    let reportMenus = []

    // Reports length
    if (reports.length) {

        reportMenus = [{ caption: 'Reports', sub_menus: reports }]
    }

    let core_modules = [{
        caption: 'Preferences',
        sub_menus: [{
            path: '/change-password',
            caption: 'Change Password'
        }]
    }]

    let allModules = [...modules, ...reportMenus, ...core_modules]

    return (
        <section className="landing">

            {/* <HotKeys focused={true} attach={window} keyMap={keyMap} handlers={handlers}> */}

            <GlobalHeader appSettings={appSettings} meta={meta} isConnected={connected} reload={loadMenus} modules={allModules} user={user} history={history}>


                {
                    loader
                        ?
                        <div className='card skeleton'><Skeleton /></div>
                        :
                        <>

                            {/* <Switch> */}

                            {/* Homepage */}
                            {!disableHomepage ? <Route exact key={'home'} path={'/'} render={(props) => <HomePageAPI config={config} {...props} />} /> : null}
                            {/* Homepage Ends */}

                            <Route exact key={'profile'} path={'/profile'} render={(props) => <Profile model={UsersAPI} {...props} />} />

                            {/* <Switch> */}
                            {/* Modules and Menus */}
                            <DefineRoute menus={modules} CustomComponents={CustomComponents} callback={(props) => {

                                setMeta({
                                    ...props
                                })

                            }} />

                            {/* <Route path={'/users'} render={() => <ModuleRoutes model={UsersAPI} />} /> */}

                            <Route path={'/reports/:id'} render={(props) => <ReportingDashboard {...props} />} />

                            <Route exact key={'change-password'} path={'/change-password'} render={(props) => <ChangePassword {...props} />} />

                            {/* </Switch> */}

                        </>}



            </GlobalHeader >

            {/* </HotKeys> */}

            <SpotlightSearch config={props.searchConfig} ref={(elem) => SettingsUtil.registerModal(elem)} />

        </section >
    );
}


/**
 * Define route
 * 
 * @param {*} param0 
 * @returns 
 */
function DefineRoute({ menus, CustomComponents, CustomModels, callback }) {

    const [routes, setRoutes] = useState([]);

    useEffect(() => {

        buildRoutes(menus);

    }, [])


    async function buildRoutes(menus) {

        // console.log(menus);

        let dynamicRoutes = prepareRoutes(menus)

        // console.log(dynamicRoutes);

        SettingsUtil.registerMenus(dynamicRoutes);

        setRoutes(dynamicRoutes);
    }


    let dynamic = [];

    function prepareRoutes(menus) {

        (menus.forEach(async (menu) => {

            dynamic.push(menu);

            if (menu.sub_menus && menu.sub_menus.length) {

                return prepareRoutes(menu.sub_menus)

            }
        }))

        return dynamic;
    }


    function printRoute(menu, index, CustomComponents, CustomModels, callback) {

        // From the path we remove any query parameters that exist in the url
        //  
        let paths = menu.path.split('?');

        // Find the route path
        let path = paths[0];

        return (
            <Route
                exact
                key={index}
                path={path}
                render={(props) => {

                    return <MenuTemplate
                        menu={menu}

                        {...menu.attributes}

                        {...props}
                        CustomModels={CustomModels}
                        CustomComponents={CustomComponents}
                        callback={(props) => {
                            callback(props);
                        }} />;
                }}
            />
        );
    }


    return (<>

        <Switch>

            {
                routes.map((menu, index) => {

                    return printRoute(menu, index, CustomComponents, CustomModels, callback)

                })
            }

        </Switch>

    </>)

}