import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ContentChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';

import { DashboardFilterComponent } from '../dashboard-filter/dashboard-filter.component';

@Component({
  selector: 'dashboard-overlay',
  templateUrl: './dashboard-overlay.component.html',
  styleUrls: ['./dashboard-overlay.component.css']
})
export class DashboardOverlayComponent implements OnInit {

  @Input() trigger: any;
  @Input() overlayWidth: any;
  @Input() optSelected: any;
  @Input() isOverlayOpen: any;
  @Input() data: any;
  @Output() onClose: EventEmitter<any> = new EventEmitter();
  @Output() onSelect: EventEmitter<any> = new EventEmitter();
  
  @Output() selected: EventEmitter<any> = new EventEmitter();
  
  @ViewChild('filterContainer', { read: ViewContainerRef }) set filterContainer(ref: any) {
    console.log('---container---',ref);
    if(ref){
        this.container = ref;
        setTimeout(() => {
            this.loadContainer();
        }, 200);
    }
  };
  
  container: any;
  compRef: any;
  
  constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
      this.selected.subscribe(
         event => {
             this.emitOnSelect(event);
         }      
      );
  }
  
  loadContainer(){
      
      if(this.optSelected == 'filterOpt'){
          this.container.detach();
          if(this.compRef){
              this.container.insert(this.compRef.hostView);
          }else{
              let compFactory =  this._componentFactoryResolver.resolveComponentFactory(DashboardFilterComponent)
              this.compRef = this.container.createComponent(compFactory);
              this.compRef.instance.pluginMetadata = this.data;
              this.compRef.instance.deviceType = this.data.get('deviceType');
              this.compRef.instance.dateFormat = this.data.get('dateFormat');
              this.compRef.instance.metadataName = this.data.get('metadataname');
              this.compRef.instance.selected = this.selected;
          }
          console.log('---compRef---',this.compRef);
      }
  }

  closeOverlay(){
      this.detachRef();
      this.isOverlayOpen = false;
      this.onClose.emit();
  }
  
  emitOnSelect(event: any){
      this.detachRef();
      this.isOverlayOpen = false;
      this.onSelect.emit(event);
  }
  
  detachRef(){
      if(this.container){
          this.container.detach();
      }
  }
  
}
