import {Component, ComponentFactoryResolver, Injector, OnInit, ViewChild, ViewContainerRef} from '@angular/core';

import {PluginLoaderService} from '../services/plugin-loader/plugin-loader.service';


@Component({
    selector: 'app-plugins-loading-demo',
    template: `
        <h1>Example of building AOT compiled plugin</h1>
        <button (click)="loadPlugin('plugin2')">Load plugin2</button>
        <div>
            <div class="plugins">
                <ng-template #targetRef></ng-template>
            </div>
        </div>
    `
})
export class PluginsLoadingDemoComponent implements OnInit {

    @ViewChild('targetRef', { read: ViewContainerRef, static: true })
    vcRef: ViewContainerRef;

    constructor(
        private injector: Injector,
        private pluginLoader: PluginLoaderService,
        private cfr: ComponentFactoryResolver
    ) {}

    ngOnInit() {
        this.loadPlugin('plugin1');
    }

    loadPlugin(pluginName: string) {
        this.pluginLoader.load(pluginName).then((moduleType: any) => {
            const entry = moduleType.entry;
            const componentFactory = this.cfr.resolveComponentFactory(entry);
            this.vcRef.createComponent(componentFactory, undefined, this.injector);
        });
    }

}
