import { Injectable, EventEmitter } from '@angular/core';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';
import { Observable } from 'rxjs';

declare var callDataModel: any;

@Injectable()
export class DashboardDatamodelService {
    
    dmResponseSubjects: any={};
    isWaiting = false;
    
    getDataModelData(dataModelName: any, filterParameter: any, scopeKey: any, isRefresh: any, isDrillDown: any, isFilterApplied: any): Observable<any>
    {
        console.log('In getDataModelData',dataModelName, filterParameter, scopeKey, isRefresh, isDrillDown, isFilterApplied);
        console.log('In getDataModelData dmResponseSubjects',this.dmResponseSubjects);
        
        if( isDrillDown && this.dmResponseSubjects[dataModelName] && !isRefresh && !isFilterApplied) //First Preference to Cache Data
        {
            return this.dmResponseSubjects[dataModelName].respSubj;
        }
        else
        {
            var dmConfig={
                dataModelName:dataModelName,
                datasourceKey:dataModelName,
                scopeParams:filterParameter,
                scopeKey:scopeKey,
                isRefresh:isFilterApplied || isRefresh
            };
            var defaultMsg = {"reponse": "loading"};
            
            var responseObj = {
               "status" : "pending",
               "respSubj" : new BehaviorSubject<any>(defaultMsg),
               "config" : dmConfig
            };
            
            this.dmResponseSubjects[dataModelName] = responseObj;
            
			//Changes for remove blocking of datamodel call
            if(!this.isWaiting || isRefresh){
            //if(isRefresh){
                this.callDataModelFunc(dmConfig);
            }
            
            return this.dmResponseSubjects[dataModelName].respSubj;
        }
         
    }
    
    callDataModelFunc(dmConfig: any)
    {
        this.isWaiting = true;
        var onSuccess = this.onSuccess.bind(this);
        var onError = this.onError.bind(this);
        callDataModel(dmConfig, onSuccess, onError);
    }
    
    onSuccess(dataModelName: any, resp: any) 
    {
        console.log("Data model loaded successfully for: ",dataModelName,resp);
        
        if(resp && typeof resp === "string"){
            resp = JSON.parse(resp);
        }
        this.dmResponseSubjects[dataModelName].status = "loaded";
        this.dmResponseSubjects[dataModelName].respSubj.next(resp);
                
        var pendingKey = Object.keys(this.dmResponseSubjects).filter(key => this.dmResponseSubjects[key].status == 'pending')[0];
        
        if(pendingKey){
        	//Added By Pravin K on 12-JUL-20[Fot the datamodel download issue in ios app] START
        	var config = this.dmResponseSubjects[pendingKey].config;
        	if(! config.isRefresh )
        	{
        		config.isRefresh = true;
        	}
        	console.log("Data model loaded  config",config);
        	
            this.callDataModelFunc(config);
            //Added By Pravin K on 12-JUL-20[Fot the datamodel download issue in ios app] END
        }else {
            this.isWaiting = false;
        }
    }
    
    onError() 
    {
        console.log("Eror while loading Data model");
        var pendingKey = Object.keys(this.dmResponseSubjects).filter(key => this.dmResponseSubjects[key].status == 'pending')[0];
        
        if(pendingKey){
            this.callDataModelFunc(this.dmResponseSubjects[pendingKey].config);
        }else {
            this.isWaiting = false;
        }
    }

    /*
    onSuccessPreload(dataModelName, resp) 
    {
        console.log("Data model loaded successfully for: ",dataModelName,resp);
    }
    
    onErrorPreload() 
    {
        console.log("Eror while loading Data model");
    }
    preloadDataModel(dataModelName, isRefresh)
    {
        var dmConfig={
            dataModelName:dataModelName,
            datasourceKey:dataModelName,
            scopeParams:'',
            scopeKey:'',
            isRefresh: isRefresh
        };
        var onSuccess = this.onSuccessPreload.bind(this);
        var onError = this.onErrorPreload.bind(this);
        callDataModel(dmConfig, onSuccess, onError);
    }
    */
    preloadDataModel(dataModelName: any, isRefresh: any) : Observable<any>
    {
        console.log('In preloadDataModel',dataModelName, isRefresh);
        console.log('In preloadDataModel dmResponseSubjects',this.dmResponseSubjects);       

        if(  this.dmResponseSubjects[dataModelName] )
        {
            return this.dmResponseSubjects[dataModelName].respSubj;
        }
        else
        {
            var dmConfig={
                dataModelName:dataModelName,
                datasourceKey:dataModelName,
                scopeParams:'',
                scopeKey:'',
                isRefresh: isRefresh
            };
            var defaultMsg = {"reponse": "loading"};
            
            var responseObj = {
               "status" : "waiting",
               "respSubj" : new BehaviorSubject<any>(defaultMsg),
               "config" : dmConfig
            };
            
            this.dmResponseSubjects[dataModelName] = responseObj;
            
            //Changes for remove blocking of datamodel call
			//if(!this.isWaiting || isRefresh){
            if(isRefresh){
                this.callDataModelFunc(dmConfig);
            }
            
            return this.dmResponseSubjects[dataModelName].respSubj;
        }
    }
    
}