import React, { useState, Suspense, useEffect, lazy, Component } from 'react';

import { BaseLoaderAPI } from './../../models/';

import { GlobalMenuProvider, useTranslation } from './../../lib/';

// import { GlobalMenuProvider } from './../../lib/';

import translations from '../../translation.json';

import { ComponentLoader } from './../component-loader/component-loader';

export default class MenuTemplateAPI extends Component {

    constructor(props) {

        super(props);

        this.state = {
            loading: false,
            model: null,
            view: [],
            component: null,
        };

        this.loadedComponent = () => null;
        this.loadedModel = () => null;
        this.menuDetail = () => { };
    }

    /**
     * 
     */
    componentDidMount() {

        var genericComponents = require('./../../modules/');

        var genericModels = require('./../../models/')

        const { menu, callback, CustomComponents, CustomModels } = this.props;

        // console.log("Initialising menu", menu.name);

        var allComponents = {
            ...genericComponents,
            ...CustomComponents,
        }
        
        var allModels = {
            ...genericModels,
            ...CustomModels
        }

        let BaseModel = {};


        if (menu.model) {

            BaseModel = new BaseLoaderAPI(menu.model);

        }

        // ./../../../core/modules/generic/generic-list/generic-list
        // Load the component with path
        // this.loadedComponent = LoadAsyncComponent(() => require(`./../../../core/modules/generic/generic-list/generic-list`));

        // this.loadedComponent = LoadAsyncComponent(() => require(`./../../../${menu.page.path}`));

        // console.log('menu', menu);
        if (menu && menu.page && (menu.page.identifier || menu.page.path)) {

            // if (menu.caption == "Demo") {

            //     menu.page.remote_entry_path = 'http://localhost:8086/remoteEntry.js';
            //     menu.page.sub_name = "Demo";

            // } else {

            //     menu.page.remote_entry_path = 'http://localhost:8085/remoteEntry.js';
            //     menu.page.sub_name = "Tokens";

            // }

            let identifier = menu.page.identifier || menu.page.path;

            if (identifier && allComponents[identifier]) {

                this.loadedComponent = allComponents[identifier]

            }

            // console.log('menu 1', menu);


            // this.loadedComponent = LoadAsyncComponent(() => require(`./../../${menu.page.path}`));

            // this.loadedComponent = LoadAsyncComponent(() => require(`./../../${menu.page.path}`));

        }


        if (menu && menu.model_id) {

            if (menu.model_id && allModels[menu.model.name]) {

                this.loadedModel = allModels[menu.model.name]

            } else {

                // BaseModel = this.loadedModel[menu.model.name];

                this.loadedModel = BaseModel

                // if (this.allModels[menu.model.name]) {

                //     BaseModel = this.loadedModel[menu.model.name];
                // }


            }


            // this.loadedComponent = LoadAsyncComponent(() => require(`./../../${menu.page.path}`));

            // this.loadedComponent = LoadAsyncComponent(() => require(`./../../${menu.page.path}`));

        }


        // this.loadedModel = require('./../../../models/');

        // If there is model 
        // if (menu.model.name) {

        //     if (this.loadedModel[menu.model.name]) {

        //         BaseModel = this.loadedModel[menu.model.name];
        //     }

        // } else {

        // }

        callback({ menu, model: this.loadedModel });

        this.setState({ loading: true, component: this.loadedComponent, model: this.loadedModel });

    }

    render() {
        const { props } = this;

        const { menu,settings } = this.props;

        const { loading, model, menuDetail } = this.state;

        const ComponentLoaderForParticulatMenu = this.loadedComponent;

        // Parse the attrbutes for the menu to customize the menu
        let attributes = {};

        let languageString = {};

        if (menu.attributes) {
            if (typeof menu.attributes === 'string') {

                attributes = JSON.parse(menu.attributes);
            }
        }

        if (menu.page && menu.page.language_string) {

            languageString = JSON.parse(menu.page.language_string);

        }

        // let configuration = {
        //     ''
        // }

        return (
            <div className="menu-template">

                {/* {menu.page.mfe ? <div> */}

                {/* {
                    loading
                        ?
                        <>
                            <App menuConfig={menu} />
                        </>
                        :
                        'Loading'
                } */}

                {/* </div>
                    :
                    <div> */}


                {
                    loading && ComponentLoaderForParticulatMenu && model ? (
                        <LanguageTranslation languageString={languageString}>
                            <GlobalMenuProvider menu={menu}>
                                <ComponentLoaderForParticulatMenu
                                    {...props}

                                    {...menu}

                                    {...attributes}

                                    {...settings}

                                    menu={menu}
                                    model={model}
                                    {...props}
                                    menuDetail={menuDetail}
                                />
                            </GlobalMenuProvider>
                        </LanguageTranslation>
                    ) : null
                }

                {/* </div>} */}



            </div>
        );
    }
}

/**
 * Function to set language translations 
 */
function LanguageTranslation({ children, languageString }) {
    const { i18n } = useTranslation()

    const language = i18n.language;

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

    return children
}


// const App = ({ menuConfig }) => {

//     // Configuration to store the env of the application
//     const [configuration, setConfiguration] = useState({});

//     useEffect(() => {

//         loadConfiguration();

//     }, [])

//     /**
//      * Load the configuration 
//      */
//     async function loadConfiguration() {


//         // let domain = "qms-dubai";
//         // // let domain = window.location.host.split(".")[0];

//         // const result = await fetch(`https://hgrntky25ejsmw3zobq3u6lk3q0tploo.lambda-url.ap-northeast-1.on.aws/?domain=${domain}`).then((result) => {
//         //     return result.json();
//         // })

//         // if (result.length && result[0].other_details) {

//         //     let appConfiguration = JSON.parse(result[0].other_details);

//         //     console.log(appConfiguration);



//         //     console.log("Starting application with ", appConfiguration);

//         //     window.process = {
//         //         env: appConfiguration
//         //     }

//         //     // Setting the title
//         //     document.title = appConfiguration.REACT_APP_WEBSITE_NAME

//         //     console.log('appConfiguration',appConfiguration);

//         console.log('here 5.1', menuConfig.page.remote_entry_path);

//         setConfiguration({
//             // ...appConfiguration,

//             // CI: false,
//             // REACT_APP_API_BASE_URL: "https://qms-api-dubai.soxo.in/",
//             // REACT_APP_BRAND_LOGO: "https://firebasestorage.googleapis.com/v0/b/plucky-avatar-230914.appspot.com/o/YC%20Logo%20(4).png?alt=media&token=4eff1ae1-38f8-40e1-8c96-42f5f1277afd",
//             // REACT_APP_FOOTER_LOGO: "./assets/images/fuji-dkh.png",
//             // REACT_APP_HERO_IMAGE: "./,assets/images/casual-life.png",
//             // REACT_APP_PRIMARY_BACKEND: "SQL",
//             // REACT_APP_REGISTER_IMAGE: "./,assets/images/register.png",
//             // REACT_APP_URL: "http://localhost:3800/remoteEntry.js",
//             // REACT_APP_WEBSITE_NAME: "QMS Dubai",
//             // REACT_APP_endpoint: "https://qms-api-dubai.soxo.in/",
//             // REACT_APP_package_version: "$npm_package_version",
//             // REACT_DB_POINTER: "nura"
//             "url": menuConfig.page.remote_entry_path,
//             "scope": "Application",
//             "name": menuConfig.page.path,
//             "props": {
//                 "props1": "propsvalue"
//             }

//         });

//         // }
//     }

//     return (<ComponentLoader component={'Tokens'} configuration={configuration} />)

// };
