import { ComponentRef, EventEmitter } from '@angular/core';

import { BBPlugin } from '../core/bb-plugin';
import { BBPluginMetadata } from '../core/bb-plugin.metadata';
import { BBPluginLoader } from '../core/bb-plugin-loader';
import { setOverlayPos } from '../../components/shared/hostUrl';

//
export const PluginMetadata = BBPluginMetadata;

//
let PLUGINS: any = {};
let loadedComponentReferences: ComponentRef<BBPlugin>[] = [];
let ng2Loader: any;
//
export function ADD_PLUGINS( pluginName : string, pluginComp : any ) : void
{
    console.log( 'ADD_PLUGINS : ', pluginName, pluginComp );
    PLUGINS[pluginName] = pluginComp;
    //console.log( 'ADD_PLUGINS : ', PLUGINS );
}

//
export function INVOKE_PLUGIN(pluginName:string, pluginMetadata:any, pluginModuleInjector:any, pluginEvtEmitter:EventEmitter<any>) : ComponentRef<any>
{
    console.log('INVOKE_PLUGIN', pluginName, PLUGINS[pluginName], pluginMetadata, pluginModuleInjector);
    let compRef : ComponentRef<any> | any;
    ng2Loader = new BBPluginLoader(pluginModuleInjector);
    let container = document.getElementById(pluginMetadata["target-id"]);
    if( container )
    {
        //console.log(container,'\n\n container childNodes', container.childNodes[0]);
        container.classList.add("js-flex-container");

        let parent = document.createElement(pluginName);
        container.appendChild(parent);
 		// Added by Sonam K [Passed pluginEvtEmitter to the loadComponentAtDom] START
		//Changed by Sonam K [Added compRef for getting component reference]
        compRef = ng2Loader.loadComponentAtDom(PLUGINS[pluginName], parent, pluginMetadata, pluginName, pluginEvtEmitter);
		// Added by Sonam K [Passed pluginEvtEmitter to the loadComponentAtDom] END
        //console.log('--compRef--',compRef.instance.pluginId);
        loadedComponentReferences.push(compRef);
    }
    setOverlayPos();
    return compRef;
}

//
export function REMOVE_PLUGIN(compName:string)
{
	if(ng2Loader){
        ng2Loader.destroyComponent(compName);
    }
}

export function DETACH_PLUGIN(pluginName:string)
{
    console.log('In DETACH_PLUGIN',pluginName);
    if(ng2Loader){
        ng2Loader.detachView(pluginName);
    }
}
/*
export function EXPOSE_PLUGIN(pluginModuleInjector: any)
{
  console.log('EXPOSE_PLUGIN CALLED');
  (window as any)['AngPlugin'] = {
    loadPlugin: INVOKE_PLUGIN,
    destroyPlugin: REMOVE_PLUGIN,
    detachPlugin: DETACH_PLUGIN,
    pluginConfig: PluginMetadata,
    pluginMI: pluginModuleInjector,
    pluginEvtEmitter: EventEmitter//,
    //zone: _ngZone
  };
  
}
*/
