import { Component, ComponentFactoryResolver, Input, Output, ViewChild, Type, Directive, ViewContainerRef, EventEmitter, OnChanges } from '@angular/core';
import { ItemDetail } from '../../ecm-model/product-detail-model';

@Directive({
    selector: '[ecm-template-ref]',
})
 export class EcmTemplateDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
}

export class EcmTemplateItem {

    public itemDetail: any
    constructor(public component: Type<any>) {}
    
    public setItemDetail(itemDetail: any){
        this.itemDetail = itemDetail;
    }
}

export interface EcmTemplateInterface {
    itemDetail: ItemDetail;
    scrollToReviews: any;
    doActivity: any;
}

@Component({
  selector: 'ecm-template',
  templateUrl: './ecm-template.component.html',
  styleUrls: ['./ecm-template.component.css']
})
export class EcmTemplateComponent implements OnChanges {
    
    @Output() scrollToReviews = new EventEmitter();
    @Output() doActivity = new EventEmitter();
    
    @Input('ecmTemplate') ecmTemplate: EcmTemplateItem;
    @Input('itemDetail') itemDetail:ItemDetail;
    
    @ViewChild(EcmTemplateDirective) ecmTemplateDir: EcmTemplateDirective;
   
    constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
    
    loadComponent(ecmTemplate){
        console.log("Ecm-Template Loader Called");
    
        let ecmTemplateItem = ecmTemplate;

        console.log("ecmTemplateItem" + ecmTemplateItem.component);
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ecmTemplateItem.component);

        let viewContainerRef = this.ecmTemplateDir.viewContainerRef;
        viewContainerRef.clear();

        let componentRef = viewContainerRef.createComponent(componentFactory);
        console.log("ecmTemplateItem.itemDetail in template"+ecmTemplateItem.itemDetail);
        (<EcmTemplateInterface>componentRef.instance).itemDetail = ecmTemplateItem.itemDetail;
        (<EcmTemplateInterface>componentRef.instance).scrollToReviews = this.scrollToReviews;
        (<EcmTemplateInterface>componentRef.instance).doActivity = this.doActivity;
    }
    
    ngOnChanges(){
        console.log("OnChanges of Ecm-Template Called");
        this.loadComponent(this.ecmTemplate);
    }
}
