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';
// Temporary commented
// import { setOverlayPos } from '../../components/shared/hostUrl';
import { changeTheme } from './theme-selector-util';

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('Print ADD_PLUGINS:::::::', pluginName, pluginComp );
    PLUGINS[pluginName] = pluginComp;
}

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>;
    ng2Loader = new BBPluginLoader(pluginModuleInjector);
    let container = document.getElementById(pluginMetadata["target-id"]);
    if( container )
    {
        container.classList.add("js-flex-container");
        let parent = document.createElement(pluginName);
        container.appendChild(parent);
        compRef = ng2Loader.loadComponentAtDom(PLUGINS[pluginName], parent, pluginMetadata, pluginName, pluginEvtEmitter);
        loadedComponentReferences.push(compRef);
    }
    // Temporary commented
    // setOverlayPos();
    return compRef;
}

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

export function DETACH_PLUGIN(visualName:string)
{
    console.log('In DETACH_PLUGIN',visualName);
    if(ng2Loader){
        ng2Loader.detachView(visualName);
    }
}

export function EXPOSE_PLUGIN(pluginModuleInjector: any)
{
  console.log('Print EXPOSE_PLUGIN CALLED pluginModuleInjector:::::::',pluginModuleInjector);
  window['add-user-taskPlugin'] = {
    loadPlugin: INVOKE_PLUGIN,
    destroyPlugin: REMOVE_PLUGIN,
    detachPlugin: DETACH_PLUGIN,
    pluginConfig: PluginMetadata,
    pluginMI: pluginModuleInjector,
    pluginEvtEmitter: EventEmitter//,
    //zone: _ngZone
  };
  (window as any)['setAngThemeColor'] = changeTheme;
}
