import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { ContentsSandbox } from '../shared/sandbox/content.sandbox';
import { HtmlContentManagerService } from './html-content-manager.service';

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

    @Output() onAbort: EventEmitter<any[]> = new EventEmitter();
    totalPages: any;
    selectedPages = 0;
    htmlFileSelected: any = [];
    importantPages: any = [];
    docId: any;
    docName: any;
    userName: any;// name for transaction customer
    profUrl: any; //profile for transaction customer
    hostUrl: any;
    content: any; // have info of selected content (pdf)
    locationURL: any;
    /*  isAddPage;*/
    // fileData: any[];//pages of html-manager
    fileData: any;//pages of html-manager
    // TODO #data from server

    pages: HTMLPage[] = [];
    private pageMap: Map<string, HTMLPage> = new Map<string, HTMLPage>();


    constructor( public contentSandbox: ContentsSandbox, public htmlContentManagerService: HtmlContentManagerService ) { }
    ngOnInit() {
        this.hostUrl = this.contentSandbox.getHostUrl();
        console.log( "hostUrl====>", this.hostUrl );

        this.htmlContentManagerService.getData().subscribe( (data: any) => {
            this.fileData = <any>data;
            console.log( "get html json data = >", this.fileData );
            ///FOR MAKING HTMLFILES SELECTED BY DEFAULT ON ADD OF NEW TRANSACTION START
            /* this.isAddPage = this.contentSandbox.pageSelectionDetails["isAdd"];
             console.log("isAddPage for slection",this.isAddPage)*/
            ///FOR MAKING HTMLFILES SELECTED BY DEFAULT ON ADD OF NEW TRANSACTION END

            ///FOR SHOWING HTMLFILES SELECTED ON A TRANSACTION START
            var pageSelectionDetails = this.contentSandbox.pageSelectionDetails["selectedPagesSeq"];
            ///FOR SHOWING SELECTEDPAGE SEQUENCE
            console.log( "pageSelectionDetails = >", pageSelectionDetails );
            if ( pageSelectionDetails ) {
                this.htmlFileSelected = pageSelectionDetails.split( ',' );
                console.log( "ghtmlFileSelected = >", this.htmlFileSelected );
            }
            ///FOR SHOWING IMPORTANTPAGE SEQUENCE
            var importantPagesSeq = this.contentSandbox.pageSelectionDetails["importantPagesSeq"];
            if ( importantPagesSeq ) {
                this.importantPages = importantPagesSeq.split( ',' );
                console.log( "important = >", this.importantPages );
            }
            ///FOR SHOWING SELECTEDPAGE NUMBER
            this.selectedPages = this.contentSandbox.pageSelectionDetails["selectedPages"];
            console.log( "pageSelectionDetails for selected pages = >", this.selectedPages );
            ///FOR SHOWING HTMLFILES SELECTED ON A  TRANSACTION END

            this.content = this.contentSandbox.getSelectedContent();
            this.docId = this.content.docId;
            this.docName = this.content.docName;

            var idx = this.docName.indexOf( '.zip' );
            var fileName = this.docName.substring( 0, idx );

            this.locationURL = this.fileData[0].locationURL;
            console.log("location url for host",this.locationURL);

            const pagesArray: HTMLPage[] = [];
            for ( const pageUrl of this.fileData[0].pages ) {
                const htmlPage: HTMLPage = {
                    identity: pageUrl.fileName,
                    url: `${this.locationURL}/${pageUrl.fileName}`,
                    isSelected: false,
                    isImportant: false
                };

                if ( this.htmlFileSelected.indexOf( htmlPage.identity ) != -1 ) {
                    htmlPage['isSelected'] = true;
                    console.log( "page---", htmlPage );
                    if ( this.importantPages.indexOf( htmlPage.identity ) != -1 ) {
                        htmlPage['isImportant'] = true;
                        console.log( "page IsImportant---", htmlPage );
                    }

                }
                pagesArray.push( htmlPage );
            }
            this.pages.push( ...pagesArray );
            this.setPageMap();

            /*  if(this.isAddPage)
                {
                    this.onAddNewPage();
                }*/
            this.totalPages = this.pageMap.size;
        } );

        this.profUrl = this.hostUrl + "/ibase/resource/images/users/default.png";
        this.userName = this.contentSandbox.selectedTemplate; //To display username
    }

    setPageMap(): void {
        for ( const page of this.pages ) {
            const identity = page.identity;
            this.pageMap.set( identity, page );
        }

    }

    loadHTMLPage( event: any ): boolean {
        const imgElement = event.target;
        console.log( "imgElement ===>", imgElement )
        this.setWebPage( imgElement );

        imgElement.remove();

        return true;
    }

    setWebPage( imgElement: HTMLImageElement ): void {
        // const pageUrl = this.hostUrl + imgElement.dataset.pageUrl;
        const pageUrl = this.hostUrl + imgElement.dataset['pageUrl'];

        console.log( "pageUrl for inage LEME ===>", pageUrl );
        // const pageIdentity = imgElement.dataset.pageIdentity;
        const pageIdentity = imgElement.dataset['pageIdentity'];

        console.log( "pageIdentity for inage LEME ===>", pageIdentity );
        const iframe: any = imgElement.nextSibling;

        // this.cancelIframeScroll(iframe);

        iframe.dataset.pageIdentity = pageIdentity;
        iframe.src = pageUrl;
    }

    private cancelIframeScroll( iframe: HTMLIFrameElement ): void {
        const onload = function() {
            try {
                const iDocument: any = iframe.contentDocument;
                console.log( "iDocument ===>", iDocument )
                iDocument.body.style.overflow = 'hidden';
            } catch ( ex ) {
                console.error( 'Exception ', ex );
            } finally {
                iframe.removeEventListener( 'load', onload );
                console.log( "iframe  removeEventListener ===>", iframe )
            }
        };

        iframe.addEventListener( 'load', onload );
        console.log( "iframe  addEventListener ===>", iframe )
    }

    public onPageSelect( event: MouseEvent ): void {
        const source: any = event.target;
        const identity = source.dataset.pageIdentity;
        const page: any = this.pageMap.get( identity );
        page.isSelected = !page.isSelected;

        if ( !page.isSelected ) {
            page.isImportant = false;
            this.selectedPages--;
            this.htmlFileSelected = this.htmlFileSelected.filter( (file: any) => file != page.identity );
        } else {
            this.selectedPages++;
            this.htmlFileSelected.push( page.identity );
        }
    }

    public onImportantClicked( identity:any ): void {
        //      this.importantPages=[];  
        const page: any = this.pageMap.get( identity );
        console.log( "page for importanat=>", page );
        page.isImportant = !page.isImportant;

        if ( !page.isImportant ) {
            this.importantPages = this.importantPages.filter( (file: any) => file != page.identity );
        } else {
            this.importantPages.push( page.identity );
            console.log( "!page.isImportant==>", this.importantPages );
        }
    }

    selectAll( event: any ) {
        console.log( "event for toggle==>", event );
        this.htmlFileSelected = [];

        if ( !event.checked ) {
            this.importantPages = [];
        }
        this.pageMap.forEach(
            page => {
                page.isSelected = event.checked;
                if ( event.checked ) {
                    this.htmlFileSelected.push( page.identity );
                }
            }
        );
        if ( event.checked ) {
            this.selectedPages = this.pageMap.size;
        }
        else {
            this.selectedPages = 0;
        }
    }

    onError( imageElement: any, description: any ) {
        var targetImg = imageElement.target;
        var errorSrc: string = this.hostUrl + '/ibase/CustomMenuImageServlet?fldValue=' + description + '&object=&objName=&ALT_FLD_VALUE=' + description + '&isOval=true';
        targetImg.src = errorSrc;
    }

    doneHtml() {

        console.log( 'Final selected files ', this.htmlFileSelected );

        let selectedPages = this.htmlFileSelected.join( "," );
        console.log( 'selected pages after spli==>', selectedPages );
        let selectedPagesStr: String = "";
        selectedPagesStr = selectedPages;
        console.log( 'selectedPagesStr==>', selectedPages );
        //      //for important
        let importantPagesArr = this.importantPages.join( "," );
        let importantStr: String = "";
        importantStr = importantPagesArr;
        console.log( 'importantStr==>', importantStr );

        //for important
        // update page_info   
        let selectedTemplate = this.contentSandbox.selectedTemplate;
        this.contentSandbox.updateSelectedTranObjects( selectedTemplate, selectedPages.length, selectedPagesStr, importantStr );
        console.log( 'contentSandbox after update==>', this.contentSandbox );

        console.log( "ALL STORED  selectedTranObjS : ", this.contentSandbox.selectedTranObjects );
    }


    /*onAddNewPage()
    {
        this.htmlFileSelected = [];
        this.pageMap.forEach(
            page => {
                        page.isSelected = true;
                        this.htmlFileSelected.push(page.identity);
                        console.log("for isAddPage html selected push==>",this.htmlFileSelected);
                        
                        let selectedPages = this.htmlFileSelected.join(",");
                        console.log("selectedPages for isAddPage html selected push==>",selectedPages)
                        let selectedPagesStr : String = "";
                        selectedPagesStr = selectedPages ;
                        console.log("selectedPagesStr for isAddPage html selected push==>",selectedPagesStr)
                        let importantPagesArr = this.importantPages.join(","); ;
                        let importantStr : String = "";
                        importantStr = importantPagesArr ;
                        let selectedTemplate = this.contentSandbox.selectedTemplate;
                        this.contentSandbox.updateSelectedTranObjects(selectedTemplate, selectedPages.length, selectedPagesStr, importantStr);
                        console.log('contentSandbox for isAddPage after update==>',this.contentSandbox);
                    }
                )
         this.selectedPages = this.pageMap.size;
      }*/
}


export interface HTMLPage {
    identity: string;
    url: string;
    isSelected: boolean;
    isImportant: boolean;
}
