import { Component, OnInit, ViewChild, TemplateRef, HostListener, OnChanges, Input, AfterViewInit, ElementRef, NgZone, ViewEncapsulation } from '@angular/core';
import { ComponentPortal, Portal, TemplatePortal } from '@angular/cdk/portal';
import { PipeTransform, Pipe } from '@angular/core';
import { Content } from '../shared/models';
import { ContentsSandbox } from '../shared/sandbox';
import { ContentService } from '../shared/services/content.service';
import { RESIZE_OBSERVABLE } from '../shared/window-resize';

import { IntersectionPipe } from '../shared/pipes/intersection.pipe';
import { HavingPipe } from '../shared/pipes/having.pipe';
import { UnionPipe } from '../shared/pipes/union.pipe';

declare var saveDocInContentLibrary: any;
export enum KEY_CODE {
    ESCAPE = 27,
}

@Component( {
    selector: 'content-view',
    templateUrl: './content-view.component.html',
    styleUrls: ['./content-view.component.css'],
    encapsulation: ViewEncapsulation.None,
    providers : [IntersectionPipe ,HavingPipe,UnionPipe]
} )
export class ContentViewComponent implements OnInit, AfterViewInit {

    contentData: any;
    @Input() searchValue: any;
    column: string = 'refSerDescr';
    direction: number | any;
    isDesc: boolean = false;
    clientWidth: any;
	clientHeight: any;
    leftValue = '';
    isShowPinned: any;

    /* Added by Chitranga Tandel */
    refSerList: any[] =[];
    docIdList: any =[];
    refSeriesList: any = [];
    refSerArray: any = [] ;
    sortedConArray: Array<any> | any;
    visibleRefList: Array<any> = [];
    userRights: any = [];
    isMobile;
    topValue: any;
    @ViewChild('contListEl') contListEl: ElementRef | any;
    groupBy = 'docContent';
    isNullData: any;

    constructor(
                public contentSandbox: ContentsSandbox,
                public contentService: ContentService,
                public intersectionPipe: IntersectionPipe,
                public unionPipe: UnionPipe,
                public differencePipe: HavingPipe,
                public zone: NgZone
               ) {
        let index = window.location.pathname.indexOf('E12BROWSER');
        
        if(index == -1){
            this.isMobile = true;
        }
    }

    @HostListener( 'window:keyup', ['$event'] )
    keyEvent( event: KeyboardEvent ) {
        if ( event.keyCode === KEY_CODE.ESCAPE ) {
            this.contentService.resetSelectedList();
        }
    }

    ngOnInit() {
        this.clientWidth = document.documentElement.clientWidth;
		this.clientHeight = document.documentElement.clientHeight;
		console.log('clientHeight In Content-View::',this.clientHeight);
		if(this.isMobile){		    
    		//this.topValue = this.clientHeight - 183 - 26;
    		this.topValue = this.clientHeight - 233;
		}
		
        this.setLeftValue( this.clientWidth );

		// changed by Abhishek T on 05-Sep-2019 START
		// removed debounceTime filter from resize event observable
        RESIZE_OBSERVABLE.subscribe(() => {
            this.clientWidth = document.documentElement.clientWidth;
            this.setLeftValue(this.clientWidth);
            
            if (this.isMobile)
            {            
                this.clientHeight = document.documentElement.clientHeight;
    		    //this.topValue = this.clientHeight - 183 - 26;
    		    this.topValue = this.clientHeight - 233;
                this.zone.run(() => {
                    console.log('view refreshed');
                });
                console.log('clientWidth,clientHeight,topValue---',this.clientWidth,this.clientHeight,this.topValue);
            }

        });
		// changed by Abhishek T on 05-Sep-2019 END
        this.contentService.onSelectRefSer.subscribe( refSer => {
            this.getRefSeriesList( refSer ); //On selection of bb-option
        } );
        this.contentService.onGroupByChange.subscribe( groupByOpt => {
            this.groupBy = groupByOpt;
            this.initData();
        } );
        this.contentService.onFilterPin.subscribe(
            isShowPinned => {
                if ( isShowPinned ) {
                    this.isShowPinned = true;
                }
                else {
                    this.isShowPinned = false;
                }
                this.contentService.isPinnedContent = false;
            }
        );
        
        this.contentSandbox.contentList$.subscribe(
                (contentData: any) => {
                    this.contentData = contentData;
                    if ( contentData && contentData.userDocContents ){
                        this.initData();
                          //this.getRefSeriesList(this.refSeriesList);
                    }
                }
        );
        
       this.userRights= this.contentSandbox.userRights;

    }

    initData() {
        
        if(this.contentData.result && this.contentData.result.status == 'Success' && this.contentData.userDocContents.length == 0)
        {
            this.isNullData = true;
        }
        
        this.visibleRefList = [];
        if(this.groupBy == 'docContent')
        {
            var docTypeList: any = {};
            this.contentData.userDocContents.forEach(
                (doc: any) => {
                   var docTypeContents = docTypeList[doc.docType] || [];
                   docTypeContents.push(doc);
                   docTypeList[doc.docType] = docTypeContents;
                }
            );
            console.log('docTypeList in initData() :',docTypeList);
            
            var docTypes = Object.keys(docTypeList) || [];
            docTypes.forEach(
                docType => {
                    this.pushVisibileList(docType, docTypeList[docType]);
                }
            );
        }
        else if(this.groupBy == 'association')
        {           
            //console.log('contentData on ngOnChanges of content-home',new Date(),this.contentData);
            this.docIdList = [];
            //console.log('******this.docReferencerActual ::',this.contentData);
                for ( let item of this.contentData.userDocContents ) {
                    this.docIdList.push( item.docId );
                    //console.log("gotRefSeries :::::::::::::",this.getRefSerDescr('EAPAPP'));
                }
                this.getAllRefSeriesList();
                //console.log('******this.sortedConArray ::',this.sortedConArray);
                this.sortedConArray =[];
                //console.log('******this.sortedConArray  after::',this.sortedConArray);
                for ( let refSerA of this.refSerArray ) {
                    // this.groupByRefSer(this.contentData.userDocContents, refSerA);
                    let refContents = this.contentData.userDocContents.filter(
                        (content: any) => {
                            for ( var index = 0; index < content.REFERENCES.length; index++ ) {
                                if ( content.REFERENCES[index].refSer == refSerA ) {
                                    return content.REFERENCES[index].refSer === refSerA;
                                }
                            }
                        } );
                    //console.log("getRefSerDescr before ",refSerA);
                    this.sortedConArray.push( {
                        refSerDescr: this.getRefSerDescr( refSerA ),
                        contents: refContents
                    } );
                }
                //console.log('sortedConArray----',this.sortedConArray);
                this.visibleRefList = this.sortedConArray;
                this.sort( this.column );
                this.getRefSeriesList(this.refSeriesList);
        }
    }

    addContent() {
        //console.log('getPluginMetadata', this.contentSandbox.contentConfig);
        saveDocInContentLibrary( this, 'attachedCallback',  this.contentSandbox.contentConfig );
    }

    attachedCallback( data: any ) {
        //console.log( 'attachedCallback called', data );
        //this.contentSandbox.addContent( data.DOC_ID );
        this.contentSandbox.emitOnContentAttached();
    }

    sort( property: any ) {
        this.isDesc = !this.isDesc; //change the direction    
        this.column = property;
        //this.direction = this.isDesc ? 1 : -1;
        this.direction = 1;
    };

    setLeftValue( value: any ) {
        if ( value < 1000 ) {
            this.leftValue = ( value - 60 ) + 'px';
        } else {
            this.leftValue = '';
        }
    }
    
    getRefSeriesList( refSer: any ) {
        //console.log("refSer in sortByRefSeriesList ",refSer ,this.refSerList.length ,Object.keys(refSer).length);
        if ( Object.keys( refSer ).length == 0 ) {
            //console.log("length became zero::::" ,this.sortedConArray);
            this.visibleRefList = this.sortedConArray;
        }
        else {
            let serIdx = refSer.indexOf( "ALL" );
            //console.log("serIdxserIdx " ,serIdx );
            if ( serIdx != -1 ) {
                this.visibleRefList = this.sortedConArray;
            }
            else {
                this.refSeriesList = refSer;
                //console.log("this.refSeriesList" ,this.refSeriesList );
                this.sortByRefSeriesList( this.refSeriesList );
            }
        }
    }

    sortByRefSeriesList( refSeriesList: any ) {
        let transformResult: any = {};
        let firstArray =[];
        let secondArray =[];
    
        //console.log("refSeriesList ",refSeriesList)
        for ( let refSer of refSeriesList ) {
            //console.log("refSer :::::::",refSer);
            transformResult[refSer] =
                ( this.transform( this.contentData.userDocContents, refSer )[0] );
            //console.log("transformResult =======",transformResult , refSer);
            firstArray = transformResult[this.refSeriesList[0]];
            secondArray = transformResult[this.refSeriesList[1]];
            this.getUnionInterSection( firstArray, secondArray );
        }
        //console.log("transformResult ======= whole ", transformResult ,this.refSeriesList[0],this.refSeriesList[1]);
    }

    getAllRefSeriesList()
    {
        this.refSerArray = [];
        if(this.contentData.userDocContents)
        {
          for (var index = 0; index < this.contentData.refSerList.length; index++)
          {
            this.refSerArray.push(this.contentData.refSerList[index].refSer);
          }
            this.refSerArray.push('_OTHER');
        }
     
        console.log("this.AllrefSerArray in content - home  :::",this.refSerArray);
    }
    
     transform(value: any, refser: any)
    {
        var groupedObj = value.reduce((prev: any, cur: any)=> {
            var foundRefSer = cur.REFERENCES.find( (key: any) => {
            if( key.refSer === refser ) 
                    return key; 
                } 
                );
               // console.log("foundRefSer",foundRefSer);
              if( foundRefSer )
              {
                if(!prev[0]) 
                {
                    //console.log("[cur.docId] ",[cur.docId]);
                    prev[0] = [cur.docId];
                } 
                else 
                {
                    prev[0].push(cur.docId);
                }
               }
              return prev;
            }, {}
        );
        //console.log("groupedObj ::::",groupedObj);
        return groupedObj;
    };
    

    getUnionInterSection(firstArray: any ,secondArray: any)
    {
        let objByRef;
        let otherListObj:any =[];
        let firstListObj:any = [];
        let secondListObj:any = [];
        let intersectionListObj:any =[];
        let uninqOfSecond;
        let uninqOfFirst; 
        let otherList ;
        let intersectionList ;
        let unionList
        
        this.visibleRefList = [];  
        if(firstArray && secondArray || firstArray  || secondArray)  
        {
              //console.log("FISRT ARRAY and SECOND ARRAY ::::",firstArray, secondArray , this.refSeriesList);
              intersectionList = this.intersectionPipe.transform(firstArray ,secondArray);
              //console.log("IntersectionList ::::",intersectionList);
              
              unionList = this.unionPipe.transform(firstArray , secondArray );
              //console.log("unionList ::::",unionList);
              if(firstArray)
              {
                  uninqOfFirst = firstArray;
              }
              if( secondArray)
              {
                 // console.log("this.secondArray",secondArray);
                  uninqOfFirst = this.differencePipe.transform( firstArray ,secondArray);
                  uninqOfSecond = this.differencePipe.transform(secondArray , firstArray);
              }
              // console.log("first Array diference", uninqOfFirst); 
              // console.log("second Array diference", uninqOfSecond); 
               
               if(firstArray && secondArray)
               {
                  otherList = this.differencePipe.transform(this.docIdList , unionList);
               }
                else
               {
                   otherList = this.differencePipe.transform(this.docIdList , firstArray);
               }
               for (var index = 0; index < otherList.length; index++) {
                      objByRef = this.getDimensionsByFilter(otherList[index]);
                      otherListObj.push(objByRef[0]);
                      
                }
                this.pushVisibileList( '_OTHER' ,otherListObj);
               
                for (var index = 0; index < uninqOfFirst.length; index++) {
                      objByRef = this.getDimensionsByFilter(uninqOfFirst[index]);
                       firstListObj.push(objByRef[0]);
                }
                this.pushVisibileList( this.getRefSerDescr(this.refSeriesList[0]) ,firstListObj);
               
                    if(uninqOfSecond)
                    {
                        for (var index = 0; index < uninqOfSecond.length; index++) {
                            objByRef = this.getDimensionsByFilter(uninqOfSecond[index]);
                            secondListObj.push(objByRef[0]);
                    }
                    this.pushVisibileList( this.getRefSerDescr(this.refSeriesList[1]) ,secondListObj);
                 }
               
                 if(intersectionList)
                 {
                 for (var index = 0; index < intersectionList.length; index++) {
                     objByRef = this.getDimensionsByFilter(intersectionList[index]);
                     intersectionListObj.push(objByRef[0]);
                  } 
               
                 this.pushVisibileList( this.getRefSerDescr(this.refSeriesList[0]) + ' & ' +this.getRefSerDescr(this.refSeriesList[1]) ,intersectionListObj);
                
                }
                // console.log("otherList",otherList ,otherListObj);
                // console.log("first have ", uninqOfFirst ,firstListObj);
                // console.log("second have ",uninqOfSecond ,secondListObj);
                // console.log("common have ",intersectionList ,intersectionListObj);
             
        }
        
        //console.log('Filtered visibleRefList',this.visibleRefList);
    }
    
    getDimensionsByFilter(id: any){
        return this.contentData.userDocContents.filter((x: any) => x.docId === id);
    }
    
    getRefSerDescr(refSerNew: any)
    {
        //console.log("refSerNew  refSerNew ",refSerNew);
        if(refSerNew)
        {
            if(refSerNew == '_OTHER') 
            {
                return refSerNew;
            }
            else
            {
                var obj = this.contentData.refSerList.find(function (obj: any) { return obj.refSer === refSerNew; });
                return obj.refSerDescr.charAt(0).toUpperCase() + obj.refSerDescr.slice(1);;
            }
        }  
     }
    pushVisibileList(refSerDescr: any , contentObj: any )
    {
        console.log("refSerDescr  ===> ",refSerDescr , "contentObj  ====>" ,contentObj)
        if(Object.keys(contentObj).length != 0)
            {
                this.visibleRefList.push({
                    refSerDescr: refSerDescr,
                    contents: contentObj
                });
            }
    }
    
    ngAfterViewInit(){
        console.log('After View Init',this.contListEl);
        if(this.isMobile && this.contListEl){
            var conHeight = this.contListEl.nativeElement.clientHeight;
            var bodyHeight = document.body.clientHeight - 190;
            console.log('conHeight & bodyHeight::',conHeight,bodyHeight);
            
            if(conHeight < bodyHeight){
                this.contListEl.nativeElement.style.minHeight = bodyHeight + 'px';
            }
        }
    }

}
