import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef, NgZone } from '@angular/core';
import { ContentService } from '../services/content.service';
import { DatePipe } from '@angular/common';
import { ContentsApiClient } from '../services/contentsApiClient.service';
import { ContentsSandbox } from '../sandbox';

import { Router } from '@angular/router';

declare var getAttachPluginFoBB: any;
declare var openSharePlugin: any;
declare var displayUsageDetailsLog: any;
declare var downloadFile: any;
declare var previewSingleDocument: any;

@Component( {
    selector: 'content-card',
    templateUrl: './content-card.component.html',
    styleUrls: ['./content-card.component.css'],
    providers: [DatePipe]
} )
export class ContentCard implements OnInit {

    @Input() hostUrl !: string;
    @Input() content:any;
    @Output() onSelect: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild( 'targetAttach' ) targetDiv: ElementRef | any;
    @ViewChild( 'fileTypeIcon' ) fileType: ElementRef | any;

    ASSET_IMG_URL = "dashboard/assets/images";
    isSelected:any;
    img_preview_url:any = '';
    isDummyImg:any;
    docTypeIconUrl:any;
    previewImageErrorCount = 0 ;
    clickCount = 0;
    singleClickTimer:any;
    @Input() detailOpts:any;
    @Input() userRights:any = [];

	// Added by Abhishek T on 24-Aug-19 START
    downloadMenuName: string = "Download"
    // Added by Abhishek T on 24-Aug-19 END

    //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] START
    isHostedMode : boolean = true;
    downLoadInProgress : boolean = false;
    //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] END

    constructor(
        private contentService: ContentService,
        private datePipe: DatePipe,
        private contentsApiClient: ContentsApiClient,
        private contentSandbox: ContentsSandbox, private router: Router,
        private zone:NgZone
    ) { }

    ngOnInit() {
        // For multiple selection
        /* this.contentService.onSelectContent.subscribe(
            selectedList => {
                let content = selectedList.find( x => x.docId === this.content.docId );
                if ( content ) {
                    this.isSelected = true;
                } else {
                    this.isSelected = false;
                }
            }
        );*/

        if(!this.hostUrl){
            this.ASSET_IMG_URL = "/ibase/E12BROWSER/"+this.ASSET_IMG_URL;
        }
        this.setImgUrl();
        //console.log("userRight in content -card" ,this.userRight);

		// Added by Abhishek T on 24-Aug-19 START
        if (this.userRights.indexOf("V") > -1) {
            this.setDownloadMenuName();
        }
        // Added by Abhishek T on 24-Aug-19 END

        //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] START
        const _win_ = (<any>window);
        if( _win_._getHostURL) {
            this.isHostedMode = false;
        }
        //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] END

    }

    /*
    * If file is already downloaded in file system, then
    * change download menu name as "Download Again", otherwise "Download"
    */
    setDownloadMenuName() {
       let _ = <any>window
        
       if (_.e12plugin && _.e12plugin.cordova && _.e12plugin.cordova.file && _.e12plugin.cordova.file.fileExists) {
            const fileExists = _.e12plugin.cordova.file.fileExists;

            // observe for download directory changes
            // and change directory here if required
            var directory = 'base/cache/downloads/files';
            var fileName = `${this.content.docId}_${this.content.docName}`;

            fileExists(directory, fileName, (error: any) => {
                this.downloadMenuName = !error ? "Download Again" : "Download";
            });
        }
    }

    selectContent( event:any ) {
        //console.log( '$event)---', event );

        const ctrlKey = event.ctrlKey;
        if ( !ctrlKey ) {
            this.contentService.selectedList = [];
        }
        this.onSelect.emit( this );
    }

    previewContent(){
       //console.log('double click----');
       //Added by Saitej .D To Play video on click at content-library dashboard Start
       if( !this.hostUrl && (['mp4', 'avi', 'flv', 'swf' , 'mpg', 'mpeg', 'mkv'].indexOf( this.content.fileType.toLowerCase().trim() ) >= 0 ))
       {
           //var videoSrc = "/ibase/WebITMDocumentHandlerServlet?ACTION=GET_DOCUMENT&DOC_ID="+this.content.docId+"&DOC_TYPE="+this.content.fileType;
           var videoSrc = "/ibase/rest/stream/"+this.content.docId;
           var linkData:any = {};
           linkData['linkInfo'] = { 'TargetObject' : 'bb-video', 'LinkForm' : 'LINK' , 'callBack' : this.callBackFunc.bind(this) };
           linkData['compData'] = { 'videoPath' : videoSrc, 'height' : 'calc(100vh - 67px)', 'DOC_ID' : this.content.docId, 'DOC_NAME' : this.content.docName, 'DOC_TYPE' : this.content.docType };
           this.contentSandbox.onFilePreview.emit(linkData);
       }
       else
       {
           let data = {
                   HOST_URL: '',
                   VIEW_ONLY: true,
                   DOCUMENT_ID: this.content.docId,
                   NAME: this.content.docName,
                   IS_HOSTED_MODE: true,
                   ENABLE_SWIPE: true,
                   ENTERPRISE: "",
                   DOCUMENT_TYPE:this.content.docType //Added by Sonam K
               }

           previewSingleDocument(data);
       }
//Added by Saitej .D To Play video on click at content-library dashboard End
    }

    callBackFunc(docUsageData:any)
	{
        console.log('Call back in Content Card Component',docUsageData);
        if(docUsageData)
        {
          this.contentSandbox.logDocUsage(docUsageData);
        }
    }

    onCardClick(){

        //TODO Instead of click touch to be implemented

        this.previewContent();
        //this.contentsApiClient.updateDates( this.content.docId );

		// Added by Abhishek T on 24-Aug-19 START
        setTimeout(() => {
            if (
                this.userRights.indexOf("V") > -1 &&
                this.downloadMenuName == 'Download'
            ) {
                this.setDownloadMenuName();
            }
        }, 5000);
        // Added by Abhishek T on 24-Aug-19 END

        this.contentSandbox.updateDate(this.content.docId);

        let sysdate = new Date();
        let latest_date =this.datePipe.transform(sysdate, 'yyyy-MM-dd HH:mm:ss.0');
        this.content.lastUserAccDate = latest_date;
        this.content.lastGenAccDate = latest_date;
        console.log("isSortBy of content service :: " , this.contentService.isSortBy);
        //Added to avoid bydefault sorting
        if(this.contentService.isSortBy)
        {
            this.contentService.onSelectContent.emit();
        }

        //        this.clickCount = this.clickCount+1;
        //
        //        if (this.clickCount == 1) {
        //            this.singleClickTimer = setTimeout(() => {
        //                this.clickCount = 0;
        //                //this.selectContent(event);
        //            }, 400);
        //        } else if (this.clickCount == 2) {
        //            clearInterval(this.singleClickTimer);
        //            this.clickCount = 0;
        //            this.previewContent();
        //            this.contentsApiClient.updateDates( this.content.docId );
        //        }

    }

    displayShare() {
        let data = [
                    {
                        NAME: this.content.docName,
                        ID: this.content.docId,
                        DOCTYPEATTACH: this.content.docType,
                        DESCRIPTION: this.content.descr   //Added by Sonam K for storing refDescr of posts
                    },
                ];

        openSharePlugin(this.content.docName,data);
    }

    closeNav() {
        document.getElementById( "mySidenav" )!.style.width = "0";
        document.getElementById( "main" )!.style.marginLeft = "0";
    }

    viewUsage() {
        //let contentIdList = [];
//        document.getElementById( "usage-documents-container" ).innerHTML = '';
//
//        if(document.documentElement.clientWidth < 800)
//        {
//            document.getElementById( "usage" ).style.width = document.documentElement.clientWidth+'px';
//        }
//        else
//        {
//            document.getElementById( "usage" ).style.width = "345px";
//        }
        document.getElementById( "contentUsage" );
        //contentIdList.push( this.content.docId );
        displayUsageDetailsLog( this.content.docId );
    }

    onCardPin( active:any ) {
        if ( this.contentService.isPinned ) {
            this.contentService.onFilterPin.emit( true );
        }
    }


    contentPluginViewUI:any;

    public openDialog( contentDetails:any ) {
        let contentDetail = contentDetails[0];
        //console.log( "loadImage check window.getContentsPlugin ", contentDetail );
        if ( !getAttachPluginFoBB ) {
            //console.log( "window.getContentPlugin is null" );
            return;
        }
        // Get the target element in which you want to add ContentPlugin.
        //console.log( "loadImage after check window.getContentPlugin " );

        this.contentPluginViewUI = getAttachPluginFoBB( {
            OBJ_NAME: '',
            REF_SER: contentDetail.refSer,
            REF_ID: contentDetail.refId,
            HOST_URL: "",
            DOC_TYPE: 'Attachment',
            IS_HOSTED_MODE: true || false,
            ENABLE_SINGLE_IMAGE: true
        }, this, 'contentPluginCallback' );

        //console.log( "USER _ID " + this.userData.jti );

        //let targetDiv = document.getElementById( 'targetContent' );
        /*
        console.log( this.targetDiv, 'this.contentPluginViewUI',  this.contentPluginViewUI );
        if ( this.targetDiv && this.contentPluginViewUI ) {
          this.targetDiv.nativeElement.innerHTML = "";
          this.targetDiv.nativeElement.appendChild( this.contentPluginViewUI );
        }
        */
    }

    contentPluginCallback( contentPlugin: any ) {
        contentPlugin.click();
        //console.log( 'ngAfterViewChecked', this.targetDiv, 'contentPlugin', contentPlugin );
        if ( this.targetDiv && contentPlugin ) {
            this.targetDiv.nativeElement.innerHTML = "";
            this.targetDiv.nativeElement.appendChild( contentPlugin );
            this.fileType.nativeElement.style.display = 'none';
            this.targetDiv.nativeElement.style.display = 'block';
            //invokeThumb();
            //this.targetDiv.nativeElement.click();
        }
    }

    openImg() {
         //console.log("in openImg() method of content-card")
         this.contentsApiClient.updateDates( this.content.docId );
    }

    download() {
	    // Changed by Abhishek T on 24-Aug-19 START
        let fileName = `${this.content.docId}_${this.content.docName}`;

        this.downLoadInProgress =true;  //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device]
        downloadFile(this.content.docId, fileName, this.content.docType, false, (resp: any) => {
            if (
                this.userRights.indexOf("V") > -1 &&
                this.downloadMenuName == 'Download'
            ) {
                this.setDownloadMenuName();
            }

            //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] START
            if(resp || !resp){
                this.downLoadInProgress = false;

                this.zone.run(() => {
                    console.log('.view refreshed constructor..');
                });
                console.log("resposnse received" + this.downLoadInProgress);
            }
            //Added by Sonam K on 4-Oct-19 [To show indication while files get downloading in mobile device] END

            console.log('On Download', resp);
        }, this.downloadMenuName != 'Download');
        // Changed by Abhishek T on 24-Aug-19 END
    }

    isImgDoctype( docType: string ) {

        if ( ['png', 'jpg', 'jpeg'].indexOf( docType.toLowerCase() ) >= 0 ) {
            return true;
        } else {
            return false;
        }
    }

    setImgUrl() {
        if ( ['png', 'jpg', 'jpeg'].indexOf( this.content.fileType.toLowerCase().trim() ) >= 0 ) {
            this.img_preview_url = this.hostUrl + '/ibase/DocumentViewerServlet?ACTION=GET_DOCUMENT&DOC_ID=' + this.content.docId + '&DOC_TYPE=' + this.content.fileType!.trim() + '&ENTERPRISE=Driver';
        } else if(['mp4', 'avi', 'flv', 'swf' , 'mpg', 'mpeg', 'mkv', 'zip', 'pdf'].indexOf( this.content.fileType.toLowerCase().trim() ) >= 0) {
            this.img_preview_url = this.hostUrl + '/ibase/DocumentViewerServlet?ACTION=GET_PREVIEW_IMAGE&DOC_ID=' + this.content.docId + '&ENTERPRISE=Driver';
            // this.img_preview_url = this.ASSET_IMG_URL + '/svg'+ '/video-preview.svg';
            // this.isDummyImg = true;
        } else {
            this.img_preview_url = this.ASSET_IMG_URL + '/svg/'+ this.content!.fileType!.trim()!.toLowerCase() + '-preview.svg';
            this.isDummyImg = true;
        }

        if(this.content.docType){
            var docType = this.content.docType.trim().toLowerCase().replace(' ','_');
            this.docTypeIconUrl = this.ASSET_IMG_URL + '/svg/' + docType + '.svg';
        }
    }

    brokenImage(event:any) {
        if (this.previewImageErrorCount == 0) {
            if( ['mp4', 'avi', 'flv', 'swf' , 'mpg', 'mpeg', 'mkv'].indexOf( this.content.fileType.toLowerCase().trim() ) >= 0 ) {
                this.img_preview_url = this.ASSET_IMG_URL + '/svg'+ '/video-preview.svg';
            } else {
                this.img_preview_url = this.ASSET_IMG_URL + '/svg/'+ this.content!.fileType!.trim()!.toLowerCase() + '-preview.svg';
            }

            this.previewImageErrorCount += 1;
        } else {
                this.isDummyImg = true;
                event.target.src = this.ASSET_IMG_URL + '/svg'+  '/broken-image.svg';
        }
    }

    brokenDocImage(event:any) {
        this.isDummyImg = true;
        event.target.src = this.ASSET_IMG_URL + '/svg/default_doctype.svg';
    }

    deactivate() {
        var confirmDeactivate = confirm("Confirm Deactivate ?");
        if (confirmDeactivate == true) {
            this.contentSandbox.deactivateDocContent(this.content.docId);
        }
    }

    goToAssocScreen() {
        this.contentSandbox.setSelectedContent(this.content);
        this.contentSandbox.onAssocOption.emit(true);
        this.router.navigateByUrl('assocObjects', { skipLocationChange: true });
    }

	//Added By Pankaj T. on 26-02-2020 for Import Orders from content library - start
    importOrders()
    {
        console.log('In importOrders');
        console.log('content:',this.content);
        const _win_ = (<any>window);
        _win_.createPopup({'targetId':'import-orders','componentName':'invoice-transaction', 'contentData':this.content},'popup');
    }
    //Added By Pankaj T. on 26-02-2020 for Import Orders from content library - end
}
