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

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

import { Skeleton } from 'antd'

import { GlobalHeader, ChangePassword, useTranslation, GlobalContext, ModuleRoutes, SpotlightSearch, SettingsUtil } from '../../lib';

import './landing-api.scss';

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 PropTypes from 'prop-types';

import {
    MenusAPI,
    CoreScripts,
}
    from '../../models';

/**
 * 
 * Landing file for
 * @param root0 
 * @param root0.history
 * @param root0.CustomComponents
 * @param root0.CustomModels
 * @param root0.appSettings
 * @param param0.props
 * @returns {*}
 */
export default function LandingApi({ history, CustomComponents, CustomModels, appSettings, ...props }) {

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

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

    const [connected, setConnected] = useState();

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

    const [allModules, setAllModules] = useState()

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

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

    var config = {};

    var role;

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

        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]);


    const { i18n } = useTranslation()

    //These change is done to fix when refreshing the report menu missing, but it removed because,makes another issue, ie there is continuos loading occurs for 2 times
    // useEffect(() => {

    //     if (loader) {
    //         initializeUserMenus();
    //     }
    // }, [loader]);


    useEffect(() => {

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

    }, []);

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

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

        await loadMenus(report);

    }


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

    let core_modules;

    // Reports length
    let reportMenus = []

    /**
     * 
     * 
     * @param reports
     */
    async function loadMenus(reports) {

        setLoader(true);

        // setReports(report)

        const result = await MenusAPI.getMenus(user);

        // console.log(result);

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

            // setModules(result.result);

            // result.result.map((ele) => {
            //     let languageString = JSON.parse(ele.attributes)
            //     console.log('language_string', languageString);
            //     if (languageString && languageString.languages) {

            //         const language = i18n.language;

            //         i18n.addResourceBundle(language, 'translation', languageString.languages[i18n.language]);
            //     }
            // })
        }


        // Reports length
        if (reports.length) {

            reportMenus = [{
                page: { path: "ManageReports", identifier: null },
                path: '/manage-reports',
                caption: 'Reports',
                sub_menus: reports
            }]
        }


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

        /**If there is roles assigned to the user */
        if (result && result.result && reportMenus) {

            setAllModules([...result.result, ...reportMenus, ...core_modules])

        } else {

            //If there is no roles assigned to the user
            setAllModules([...core_modules])
        }


        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);

            return filtered;
        } else {
            return [];
        }
    }

    // setAllModules([...modules, ...reportMenus, ...core_modules])

    // let core_modules = [];

    // // Reports length
    // let reportMenus = []

    // // Reports length
    // if (reports.length) {

    //     reportMenus = [{
    //         page: { path: "ManageReports", identifier: null },
    //         path: '/manage-reports',
    //         caption: 'Reports',
    //         sub_menus: reports
    //     }]
    // }

    return (
        <section className="landing">

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

            <GlobalHeader loading={loader} appSettings={appSettings} meta={meta} isConnected={connected} reload={initializeUserMenus} modules={allModules} user={user} history={history}>


                {
                    loader
                        ?
                        <div className='skeleton-wrapper'>
                            <Skeleton paragraph={{ rows: 4 }} />

                        </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} />} /> */}

                            <Route path={'/menus/:id'} render={(props) => <ModuleRoutes model={MenusAPI} />} />

                            {/* <Switch> */}
                            {/* Modules and Menus */}
                            <DefineRoute menus={allModules}

                                CustomComponents={CustomComponents}
                                CustomModels={CustomModels}


                                settings={appSettings} callback={(props) => {

                                    setMeta({
                                        ...props
                                    })

                                }} />

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


                            <Route path={'/reports/:id'} render={(props) => <ReportingDashboard CustomComponents={CustomComponents} {...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 PropTypes for the component
LandingApi.propTypes = {
    history: PropTypes.history,
    CustomModels: PropTypes.object,
    appSettings: PropTypes.object,
    props: PropTypes.array,
};


/**
 * Define route
 * 
 * @param {*} param0 
 * @returns 
 */

/**
 * @param root0 
 * @param root0.menus
 * @param root0.CustomComponents
 * @param root0.CustomModels
 * @param root0.settings
 * @param root0.callback
 * @returns {*}
 */

/**
 *
 * @param root0
 * @param root0.menus
 * @param root0.CustomComponents
 * @param root0.CustomModels
 * @param root0.settings
 * @param root0.callback
 */
function DefineRoute({ menus, CustomComponents, CustomModels, settings, callback }) {

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

    const [languagestring, setLanguagestring] = useState({});

    const { i18n } = useTranslation();

    useEffect(() => {

        buildRoutes(menus);

    }, [])


    /**
     *
     * @param menus
     */
    async function buildRoutes(menus) {

        let dynamicRoutes = prepareRoutes(menus)

        // console.log(dynamicRoutes);

        SettingsUtil.registerMenus(dynamicRoutes);

        // Prepare the language bundle
        prepareLanguageBundle({ menus: dynamicRoutes });

        setRoutes(dynamicRoutes);
    }


    let dynamic = [];

    /**
     *
     * @param menus
     */
    function prepareRoutes(menus) {

        if (menus && menus.length) {

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

                dynamic.push(menu);

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

                    return prepareRoutes(menu.sub_menus)

                }
            }))
        }


        return dynamic;
    }

    /**
     * Prepare the language bundle that accepts the menus and prepares the bundle
     * 
     * @param {*} param0 
     */
    function prepareLanguageBundle({ menus }) {

        let languageString = {};

        const language = i18n.language;

        // Load the language String from each 
        menus.forEach((menu) => {

            if (menu.attributes) {

                // try {
                // Menu Attributes
                let attributes = JSON.parse(menu.attributes);

                if (attributes && attributes.languages) {

                    let keys = Object.keys(attributes.languages)

                    keys.forEach((key) => {

                        // languageString = {      
                        //     [key]:{
                        //         ...attributes.languages[key]
                        //     }

                        // }

                        languageString[key] = {
                            ...languageString[key],
                            ...attributes.languages[key]
                        }

                        // languageString = {      
                        //     [key]:{
                        //         ...attributes.languages[key]
                        //     }

                        // }

                        i18n.addResourceBundle(key, 'translation', languageString[key]);


                    })

                    setLanguagestring(languageString);

                    // languageString = {

                    //     ...languageString,
                    //     [menu.name]:{
                    //         ...attributes.languages                            
                    //     }

                    // }

                    // Object.keys(languageString).forEach((key)=>{

                    //     i18n.addResourceBundle(key, 'translation', languageString[key]);

                    // })
                }
                // } catch (error) {

                //     console.log(error);

                // }



            }

        })

        i18n.addResourceBundle(language, 'translation', languageString[i18n.language]);

    }


    /**
     * @param root0
     * @param root0.menu
     * @param root0.index
     * @param root0.CustomComponents
     * @param root0.CustomModels
     * @param root0.callback
     * @param menu
     * @param index
     * @param CustomComponents
     * @param CustomModels
     * @param callback
     */
    function printRoute(menu, index, CustomComponents, CustomModels, callback) {

        // From the path we remove any query parameters that exist in the url
        //  
        let paths;

        //There will be path for normal menus
        if (menu.path) {

            paths = menu.path.split('?');

        } else {
            /** In case if there is no path , ie, in case of reports menu */
            menu.sub_menus.map((menus) => {

                paths = menus.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}
                        settings={settings}
                        callback={(props) => {
                            callback(props);
                        }} />;
                }}
            />
        );
    }


    return (<>

        <Switch>

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

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

                })
            }

        </Switch>

    </>)

}
