import { Component, Input, Output, EventEmitter,OnDestroy, ViewChild, ViewContainerRef, ComponentFactoryResolver, AfterViewChecked } from '@angular/core';
import { DatePipe } from '@angular/common';

import { BBPlugin, getUniqueId } from '../../plugin/core/bb-plugin';
import { BBPluginMetadata } from "../../plugin/core/bb-plugin.metadata";

import { DashboardService } from './dashboard.service';
import { FilterDataService } from './dashboard-filter/filter-data.service';

import { DashboardViewComponent } from './dashboard-view/dashboard-view.component';

@Component( {
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css'],
    providers: [DatePipe]
})
export class DashboardComponent implements BBPlugin,OnDestroy, AfterViewChecked{

    @Input() pluginId: string = getUniqueId( 'dashboard' );
    @Input() title: string | any;
    @Input() pluginMetadata: BBPluginMetadata | any; 

    @Output() selected: EventEmitter<any> = new EventEmitter();
    
    @ViewChild('viewContainer', { read: ViewContainerRef }) viewContainer: any;
    
    compRefObj: any = {};

    viewData: any;
    componentList: any;
    pageTitle: any;
    metadataname: any;
    showHeader: boolean = false;
    dashboardData: any;
    subTitleData: any;
    titleData: any;
    defaultSubtitle: any;
    compData: any;
    isLinkComponent = false;
    //Added by sunny soni for native related change for handling server call [START]
    loading = false;
    isNative: boolean = false;
    isDashboardRendered: boolean = false;
    //Added by sunny soni for native related change for handling server call [END]
    
    constructor( public dashboardService: DashboardService, private _componentFactoryResolver: ComponentFactoryResolver, public filterDataSvc: FilterDataService, private datePipe: DatePipe ) { 
        console.log('dashboard inside costructor ');
    }

    ngOnInit() 
    {
        console.log('inside ngOnInit call')
        console.log('--sunny-- this.pluginMetadata::'+this.pluginMetadata);
        console.log('--sunny-- window as any["NATIVE"]::'+(window as any["NATIVE"]));
        //Added by sunny soni for native related change for handling server call[START]
        if (window as any["NATIVE"]) {
                if (window as any["NATIVE"]["ISNATIVE"]) {
                    this.isNative = window as any["NATIVE"]["ISNATIVE"];       
                }
        }
        //Added by sunny soni for native related change for handling server call[END]
        let index = window.location.pathname.indexOf('E12BROWSER');
        
        if(index > -1){
            this.showHeader = true;
        }
        
        if ( this.pluginMetadata ) 
        {
            console.log('--sunny-- this.pluginMetadata::'+this.pluginMetadata);
            //this.metadataname = this.pluginMetadata.get( 'metadataname' );
            this.metadataname = this.pluginMetadata.metadataname;
            this.pluginId='dashboard_'+this.metadataname;
            //this.compData = this.pluginMetadata.get( 'compData' );
            this.compData = this.pluginMetadata.compData;
            console.log( 'DashboardComponent ngOnInit', this.metadataname,this.pluginMetadata,this.compData );
            if(this.compData && this.compData.targetId.indexOf('dashboard') == -1 ){
                this.isLinkComponent = true;
            }
            
            if(!this.showHeader && this.compData && this.compData.targetId.indexOf('dashboard') == -1 ){
                this.showHeader = this.compData.showHeader;
            }
            
            console.log('  showHeader ', this.showHeader);
            this.getDashboardData( this.metadataname );
        }
        
        if(!this.showHeader){            
              this.filterDataSvc.getFilterValues(this.metadataname).subscribe((filterValues: any) => {
                  if(this.dashboardData && !this.dashboardData.sub_title && filterValues && filterValues.metadataName == this.metadataname)
                  {
                    console.log(':: filter values in dashboard-component',filterValues);
                    this.setAppliedSubtitle(filterValues.values);
                  }
              });
       }
    }

    getDashboardData(metadataname: any) 
    {
        //Uncommented by sunny soni for quick access dashboard not loading problem on 12-JAN-21[START]
        //Commented by sunny soni for quick access dashboard not loading problem on 08-JAN-21[END]
        //Added by sunny soni for native related change for handling server call [START]        
        if (this.isNative) {
                this.loading = true;
        }                
        this.dashboardService.getDashboardMetadataFromServer( metadataname, (result: any) => 
        {
                if (this.isNative) {
                    this.loading = false;
                }
                if ( result ) {                                
                    if(result.status=='failure'){
                        console.log('Inside file not found');
                        alert(result.message);
                }
                if(result.status=='success')
                {
                    console.log( 'result==========', result );
                    this.dashboardData = result;
                    this.pageTitle = result.page_title;

                    //TODO for Multiple Views
                    this.viewData = result.view;
                    for(var view of this.viewData)
                    {
                        view.selected = false;
                        console.log( 'result==========', view, this.viewData )
                    }                    
                    if(this.viewData){
                        setTimeout(() => {
                            //Added by sunny soni for native related change for handling server call [START]
                            if (!this.isNative) {
                                this.renderView(this.viewData[0], false);
                            }
                            //Added by sunny soni for native related change for handling server call [END]
                            //this.renderView(this.viewData[0], false);
                        }, 2);
                    }                

                    var datasource = result.datasource;                    
                    var filters = result.filters;                  
                    
                    if(filters && filters.filter)
                    {
                        filters.filter.forEach(
                                (filterVal: any) => {                                     
                                        var colVal = this.compData[filterVal.col_name];
                                        
                                        if(colVal){
                                            if(filterVal.type == "4")
                                            {                                          
                                                var defaultDate = this.dashboardService.getDefaultDate(colVal);
                                                var defaultDateStr = this.dashboardService.formatDate(defaultDate);
                                                console.log('Final defaultDateStr:',defaultDate,defaultDateStr);
                                                filterVal.default_value = defaultDateStr;
                                            }
                                            else if(filterVal.type == "5")
                                            {
                                                var defaultMonth = this.dashboardService.getDefaultMonth(colVal);
                                                console.log('Final defaultMonth:',defaultMonth);
                                                filterVal.default_value = defaultMonth;
                                            }
                                            else
                                            {
                                                filterVal.default_value = colVal;
                                            }    
                                        }
                                }
                        );
                    }                    
                    this.dashboardService.createDataSources(metadataname,datasource, filters);                    
                    if(!this.showHeader){                    
                        var subTitle = this.dashboardService.getDashboardSubtitle(this.dashboardData);
                        this.defaultSubtitle = this.dashboardService.defaultSubtitle;
                        this.emitResponse("subtitle",subTitle);
                    }
                        
                }                        
            }
        });
        //Added by sunny soni for native related change for handling server call [END]
        //Commented by sunny soni for quick access dashboard not loading problem on 08-JAN-21[END]
        //Uncommented by sunny soni for quick access dashboard not loading problem on 12-JAN-21[END]
        /*
        //commented by sunny soni after resolved quick access dashboard not loading problem on 12-JAN-21[START]
        this.dashboardService.getDashboardMetadata( metadataname ).subscribe(
            result => {
                if ( result ) {
                    if(result.status=='failure'){
                        console.log('Inside file not found');
                        alert(result.message);
                    }
                    if(result.status=='success')
                    {
                        console.log( 'result==========', result );
                        this.dashboardData = result;
                        this.pageTitle = result.page_title;

                        //TODO for Multiple Views
                        this.viewData = result.view;
                        for(var view of this.viewData)
                        {
                            view.selected = false;
                            console.log( 'result==========', view, this.viewData )
                        }
                        if(this.viewData){
                            setTimeout(() => {
                                this.renderView(this.viewData[0], false);
                            }, 100);
                        }

                        var datasource = result.datasource;                    
                        var filters = result.filters;
                      
                        if(filters && filters.filter)
                        {
                          filters.filter.forEach(
                                  filterVal => {                                     
                                          var colVal = this.compData[filterVal.col_name];
                                          
                                          if(colVal){
                                              if(filterVal.type == "4")
                                              {                                          
                                                  var defaultDate = this.dashboardService.getDefaultDate(colVal);
                                                  var defaultDateStr = this.dashboardService.formatDate(defaultDate);
                                                  console.log('Final defaultDateStr:',defaultDate,defaultDateStr);
                                                  filterVal.default_value = defaultDateStr;
                                              }
                                              else if(filterVal.type == "5")
                                              {
                                                  var defaultMonth = this.dashboardService.getDefaultMonth(colVal);
                                                  console.log('Final defaultMonth:',defaultMonth);
                                                  filterVal.default_value = defaultMonth;
                                              }
                                              else
                                              {
                                                  filterVal.default_value = colVal;
                                              }    
                                          }
                                  }
                          );
                        }
                        this.dashboardService.createDataSources(metadataname,datasource, filters);
                        if(!this.showHeader){                    
                          var subTitle = this.dashboardService.getDashboardSubtitle(this.dashboardData);
                          this.defaultSubtitle = this.dashboardService.defaultSubtitle;
                          this.emitResponse("subtitle",subTitle);
                        }
                        
                    }
                        
                    }

            }
        );
        //commented by sunny soni after resolved quick access dashboard not loading problem on 12-JAN-21[END]*/        
    }
    //Added by sunny soni for native related change for handling server call [START]
    ngAfterViewChecked() {        
        if (this.isNative) {            
            if(this.viewData) {               
                // console.log('inside [ngAfterViewChecked] function isDashboardRendered::['+this.isDashboardRendered+']');
                if(!this.isDashboardRendered){
                    setTimeout(() => {                        
                        this.renderView(this.viewData[0], false);
                    }, 1);
                }                
            }
        }        
    }    
    //Added by sunny soni for native related change for handling server call [END]
    ngOnDestroy() 
    {
        console.log('dashboard comp ngOnDestroy..');
    }
    
    renderView(view: any, onViewSelect: any){
        console.log('renedreVIew....',view, onViewSelect);
        this.dashboardService.setSelectedViewId(view.id);
        this.viewContainer.detach();
        if( ( view.type === 'flatonly' || view.component.length == 1 ) && ( this.dashboardData.filters && this.dashboardData.filters.display=='N' ) )
        {
            this.showHeader = false;
        }
        console.log('render view showHeader ',this.showHeader);
        var compRef = this.compRefObj[view.id];
        view.selected = true;
        if(compRef){
            this.viewContainer.insert(compRef.hostView);
        }else{
            let compFactory =  this._componentFactoryResolver.resolveComponentFactory(DashboardViewComponent)
            compRef = this.viewContainer.createComponent(compFactory);
            
            compRef.instance.viewData = view;
            compRef.instance.metadataname = this.metadataname;
            compRef.instance.isLinkComponent = this.isLinkComponent || onViewSelect;
            this.compRefObj[view.id] = compRef;
        }
        console.log('---compRef---',compRef);
        //Added by sunny soni for native related change for handling server call[START]
        this.isDashboardRendered = true;
        //Added by sunny soni for native related change for handling server call[END]
    }
    
    setAppliedSubtitle(filterValues: any){
      var subTitle = "";
      console.log('subtitle ',filterValues);
      if(filterValues){
          filterValues.forEach(
                  (filter: any) => {
                      if(filter.changedValue && filter.show_ontitle == "1"){              
                          if(subTitle){
                              subTitle = subTitle + ", "
                          }
                          subTitle = subTitle + filter.col_descr + " " + filter.changedValue;
                      }
                  }
                );
                
                if(this.defaultSubtitle){
                    subTitle = subTitle + " " +this.defaultSubtitle
                }
      }
      this.emitResponse("subtitle",subTitle);
    }
  
    emitResponse(id: any, value: any){
      var response = {
          "id" : id,
          "value": value
      };
      
      if(id == "subtitle"){      
        this.subTitleData = response;
      }else if(id == "title"){
        this.titleData = response;
      }
      console.log("== emitted response in dashboard-component == ",response);
      this.selected.emit(response);
    }
    
    //public setPluginMetadata(pluginMetadata){
    public setPluginMetadata(pluginMetadata: any,pluginDashboardData: any){
        console.log( 'DashboardComponent setPluginMetadata ', pluginMetadata);
		this.pluginMetadata = pluginMetadata;
		//this.compData = this.pluginMetadata.get( 'compData' );
        this.compData = this.pluginMetadata.compData;
		console.log( 'DashboardComponent setPluginMetadata  dashboardData', this.dashboardData,pluginDashboardData);
		var filters =  this.dashboardData.filters;
		console.log('dashboardData.filters ::',filters);
		if(pluginDashboardData && pluginDashboardData.filters )
		{
		     filters =  pluginDashboardData.filters;
		}
		var  filterParams = '';
		
		console.log('filters ::',filters);
		
        if(this.compData && filters && filters.filter)
        {           
            filters.filter.forEach(
                    (filterVal: any) => {
                        
                        if(filterVal.type == "4")
                        {
                            var colVal = this.compData[filterVal.col_name];
                            //added by Sainath to resolve coaching activity dashboard old data issue-start
                            if( !colVal || colVal == undefined )
                            {
                                colVal = filterVal.default_value;
                            }
                            console.log('colVal 001==>',colVal);
                            //added by Sainath to resolve coaching activity dashboard old data issue-end
                            var defaultDate = this.dashboardService.getDefaultDate(colVal);
                            var defaultDateStr = this.dashboardService.formatDate(defaultDate);
                            console.log('Final defaultDateStr:',defaultDate,defaultDateStr);
                            filterVal.changedValue = defaultDateStr;
                        }
                        else 
                        {
                            var colVal = this.compData[filterVal.col_name];
                            if(colVal){
                                filterVal.changedValue = colVal;
                            }else {
                                filterVal.changedValue = filterVal.default_value;
                            }
                        }
                        
                        filterParams += filterVal.col_name + "=" + filterVal.changedValue + "&";
                    }
            );
            
            this.filterDataSvc.setFilterParameters(this.metadataname, filterParams, filters);
        }
    }
}
