export class DynamicJSInclude {

    constructor( groups ) {
        
        /// files to include
        this.groups = groups;

        /// components
        this.load();
    }

    
    load() { 

        this.groups.forEach( async files => { 

            this.loadComponent( files );    
        });
    } 

    /**
     * 
     * @param {array} files 
     * @returns 
     */
    loadComponent( files ) {

        if( files.length == 0 ) return;

        let file = files.shift();

        //if( file.includes('lib') ) 
            this.loadScript( file, files );
        //else            
            //this.loadModule( file, files );

    }
    

    async loadModule( url, files ) {

        await import( url ).then( res => {

            if( typeof res.default !== 'undefined' ) {

                /// rende globale l'oggetto importato
                window[ res.default.name ] = res.default;
            }

            this.loadComponent( files );            
        });
    }


    loadScript( url, files ) {

        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;

        // set the callback        
        script.addEventListener("load", () => this.loadComponent( files ) );

        // Fire the loading
        document.head.appendChild(script);
        
    }

}
