import { Component, OnInit, Input, ViewChild, ViewContainerRef, ComponentFactoryResolver, EventEmitter, ViewChildren, QueryList, ElementRef } from '@angular/core';
import { Portal,  TemplatePortalDirective } from '@angular/cdk/portal';

import { DashboardComponentComponent } from '../dashboard-component/dashboard-component.component';
import { DashboardService } from '../dashboard.service';
// import { Subscription } from 'rxjs/Subscription';
import { Subscription } from 'rxjs';

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

  @Input() viewData: any;
  @Input() metadataname: any;
  @ViewChild('drillDownContainer', { static: true, read: ViewContainerRef }) drillDownContainer: any;
  @Input() isLinkComponent: any;
  @ViewChildren('dashboardComps') dashboardComps:QueryList<DashboardComponentComponent> | any;
  @ViewChild('dashboardViewEl') dashboardViewEl: ElementRef | any;
  @ViewChild(TemplatePortalDirective) templatePortal: Portal<any> | any;

  compRef: any;
  refreshDate: any;
  respSubcription: Subscription | any;
  filterInfo: any;
  isDrillDown: any;
  isCompositeDrillDown: any;
  filters: any;
  isSingleDashboard: any;
  obj_links: any[] = [];
  defaultLinks: any = [];
  obj_name: any;
  hostUrl: any;
  ASSET_IMG_URL = "dashboard/assets/images";
  feedData: any;
  isNullData: any;
  compData: any;
    
  constructor(private _componentFactoryResolver: ComponentFactoryResolver, public dashboardService: DashboardService ) { }

  ngOnInit() {
      console.log('view data for diff components',this.viewData, this.metadataname);
      
       this.viewData.component = this.viewData.component.filter((comp: any) => comp.display === "Y");
       this.refreshDate = new Date();
       this.isSingleDashboard=(this.viewData.component.length==1);
       if(this.viewData.component && this.viewData.component.length>0)
       {
           this.compData = this.viewData.component[0];
           this.obj_links = this.compData.obj_links || [];
           this.obj_name = this.compData.obj_name;
       }
       
       this.hostUrl = this.dashboardService.getHostURL();
       if(!this.hostUrl){
           this.ASSET_IMG_URL = "/ibase/E12BROWSER/"+this.ASSET_IMG_URL;
       }
      console.log("view Component based on display",this.viewData.component,this.isSingleDashboard);
  }

  openDrillDown(selectedFieldInfo: any){

    if(this.compRef){
        this.compRef.destroy();
    }
    this.dashboardService.getDashboardMetadata( selectedFieldInfo.linkMetadata ).subscribe(
        (result: any) => {
            var datasource = result.datasource;
            var filters =  result.filters;
            this.dashboardService.createDataSources(selectedFieldInfo.linkMetadata,datasource,filters);
            
            this.drillDownContainer.detach();
            var compFactory =  this._componentFactoryResolver.resolveComponentFactory(DashboardViewComponent)
            this.compRef = this.drillDownContainer.createComponent(compFactory);
            this.compRef.instance.compRef = this.compRef;
            this.compRef.instance.viewData = result.view[0];
            this.compRef.instance.metadataname = selectedFieldInfo.linkMetadata;
            this.compRef.instance.filterInfo = selectedFieldInfo;
            this.compRef.instance.isDrillDown = true;
            this.compRef.instance.isCompositeDrillDown = selectedFieldInfo.isCompositeDrillDown;
            this.compRef.instance.filters = result.filters;
        });
  }

  refresh(){
      console.log('Dashboard Components ::',this.dashboardComps);

      var uniqueDataSources: any = [];

      if(this.respSubcription){
        this.respSubcription.unsubscribe();
      }

       this.dashboardComps.forEach(
          (comp: any) => {
              var datasourceId = comp.datasourceId;
              console.log('uniqueDataSources',uniqueDataSources);          
              if(uniqueDataSources.indexOf(datasourceId) == -1){
                uniqueDataSources.push(datasourceId);
                this.respSubcription = this.dashboardService.getDashboardData(comp.dashboardName,comp.datasourceId, comp.filterParameter, true, comp.isDrillDown, false).subscribe(
                    (resp: any) => {
                        console.log('Dashboard Response in DBView',resp);
                    }
                );
              }
          }
       );

      this.refreshDate = new Date();
  }

  closeDrillDown() {
    this.compRef.destroy();
  }

  ngAfterViewInit(){
    console.log('dashboardViewEl..AfterViewInit',this.dashboardViewEl);
    if(this.isDrillDown){
        this.dashboardViewEl.nativeElement.scrollIntoView();
    }
  }
  
  getImgSrc(link: any) {
      var thumbObj = "";
      var imgUrl;
      
      if(this.defaultLinks.indexOf(link.LinkType) === -1){
          imgUrl = this.hostUrl + "/ibase/CustomMenuImageServlet?fldValue=" +link.LinkTitle+ "&object="+thumbObj+"&objName="+this.obj_name;
      }else if(link.LinkType == 1){
          imgUrl = this.ASSET_IMG_URL + "/svg/link_view.svg";
      }
      
      return imgUrl;
  }
  performLinkAction(link: any){
      console.log('feedData in performLinkAction',this.feedData,link);
      if(link.LinkType == 'CL'){
          console.log('In link type cl');
          link.handler();
      } else if(link.LinkType == 'A' && this.isNullData){
          alert('No data');
      }else if(link.LinkType == 'A'){
          this.dashboardService.invokeAngCompLink(link, this.feedData, this.obj_name, this.templatePortal, this.compData);
      }else if(link.LinkType == 4 || link.LinkType == 7){          
          this.dashboardService.invokeDashboardLink(link, this.feedData, this.obj_name);
      }else if(this.feedData){
          this.dashboardService.invokeDashboardLink(link, this.feedData, this.obj_name);
      }else {
          alert('Please select a record.');
      }
      
      //this.closeOverlay();
  }
  
  setFeedData(rowData: any){
      this.feedData = rowData;
  }
  
  refreshComponents() 
  {
	 this.dashboardComps.forEach( (comp: any) => {
         var datasourceId = comp.datasourceId;
         console.log('refreshComponents comp :', datasourceId, comp);          
         comp.refreshData();     
     });
  }
}
