import { Component, OnInit, ViewEncapsulation, Output, EventEmitter, Input } from '@angular/core';
import { PDFDocumentProxy } from 'ng2-pdf-viewer';
import { ContentsSandbox } from '../shared/sandbox/content.sandbox';

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

  totalPages : number = 0 ;
  selectedPages: any = []; // numbers of selected pages eg 1,2,3..
  pages: any = []; //details of selected pages [{0:{...}},{1:{...}}]
  pdf_url: any ; // url to  show the pdf
  content: any ; // have info of selected content (pdf)
  profUrl: any ; // url for transaction customet
  userName: any ;// name for transaction customet
  importantPages: any = []; //To store important pages

  constructor(public contentSandbox: ContentsSandbox ) { }
  ngOnInit() {
    this.content = this.contentSandbox.getSelectedContent();
    console.log("this.content : ", this.content);
    
    if(this.content.docPages)
    {
      this.totalPages = this.content.docPages
    }

    var hosturl= this.contentSandbox.getHostUrl();
    this.pdf_url = hosturl+"/ibase/DocumentViewerServlet?ACTION=GET_DOCUMENT&DOC_ID="+ this.content.docId +"&DOC_TYPE=pdf"; 
    
    this.profUrl = hosturl+"/ibase/resource/images/users/default.png";
    this.userName = this.contentSandbox.selectedTemplate;

    if(  this.contentSandbox.pageSelectionDetails["selectedPages"]>0)
    {
      this.setSelecetdPages(this.contentSandbox.pageSelectionDetails["selectedPagesSeq"], this.selectedPages );
      if(this.contentSandbox.pageSelectionDetails["importantPagesSeq"].length>0)
      {
        this.setSelecetdPages(this.contentSandbox.pageSelectionDetails["importantPagesSeq"], this.importantPages );
      }
    }
  }

  loadComplete(pdf: PDFDocumentProxy)  
  {
    if(this.totalPages == 0)
    {
      this.totalPages = pdf.numPages;
    }

    for(var idx = 0 ; idx < pdf.numPages ; idx++ )
    {
      this.pages[ idx ] = { 'pageNumber' : idx , 'status' : false };
    }

    if(this.contentSandbox.getSelectedContent().docPages != this.totalPages)
    {
      this.contentSandbox.getSelectedContent().docPages = this.totalPages;
    }
  }

  // Event called after each page loded
  pageRender(evt: any)
  {
  	//Changed by Pravin K on 17-OCT-19[for the issue selected and important symbols not showing] START
    //var pageNumber = evt.detail.pageNumber;
    //var page = evt.target;
    console.log("pageRender-evt",evt);
    var pageNumber = evt.pageNumber;
    var page = evt.source.div
  	//Changed by Pravin K on 17-OCT-19[for the issue selected and important symbols not showing] END
  	//console.log("pageRender-page",page);
    if(page)
    {
      var pageNav = document.createElement("div");
      page.appendChild(pageNav);
      pageNav.setAttribute("pageNumber", pageNumber);
      pageNav.setAttribute("class", "pageNav");
      pageNav.innerHTML = `<span style='color:#fff;'> Page ${pageNumber} </span> <i class= "material-icons">check_circle</i>`;
      
      if( this.selectedPages.indexOf( pageNumber) != -1 )
      {
        var pageObj = this.pages[ pageNumber - 1];
        pageObj.status = true; 
        pageNav.setAttribute("class", "pageNav pageNav-selected");

        // For important while loding
        var pageImportantContainer = document.createElement("div");
        pageImportantContainer = this.addPageImportantContainer(pageNumber);
        pageNav.appendChild(pageImportantContainer);
        
        // For important 
      }
      
      var self = this;
      var displayPage = page.childNodes;
      displayPage[0].onclick = function()
      {
        var pageObj = self.pages[ pageNumber - 1];
        if( pageObj )
        {
          pageObj.status = !pageObj.status; 
        }
        if( pageObj.status )
        {
          pageNav.setAttribute("class", "pageNav pageNav-selected");
          if( self.selectedPages.indexOf(pageNumber)== -1)
          {
            self.selectedPages.push(pageNumber);
            // For important 
            var pageImportantContainer = document.createElement("div");
            pageImportantContainer = self.addPageImportantContainer(pageNumber);
            pageNav.appendChild(pageImportantContainer);
            // For important 

          }
        }
        else
        {
          pageNav.setAttribute("class", "pageNav");
          var index = self.selectedPages.indexOf(pageNumber);
          self.selectedPages.splice(index,1); 

          //For important 
          self.removeImportantContainer(pageNav);
          //For important

        }
        self.contentSandbox.pageSelectionDetails["selectedPages"] = self.selectedPages.length ;
      }  
    }
  }
 
  onSelectAllChange(evnt: any)
  {
    var pagesElnmts: any = document.getElementsByClassName("pageNav");
    for(let pageCn = 0 ; pageCn < pagesElnmts.length ;pageCn++ )
    {
      var currPage = pagesElnmts[pageCn];
      currPage.setAttribute("class", evnt.checked ? "pageNav pageNav-selected": "pageNav" );
      //for the element present on dom
       //add mamdatory
       if(evnt.checked)
       {
          let pageNo:Number = +pagesElnmts[pageCn].getAttribute("pageNumber");
          let index = this.selectedPages.indexOf(pageNo);
          if(index == -1)
          {
            var pageImportantContainer = this.addPageImportantContainer( pageNo);
            pagesElnmts[pageCn].appendChild(pageImportantContainer);
          }
       }
       else
       {
        this.removeImportantContainer(pagesElnmts[pageCn]);
       }
       //add mamdatory
    }
    
    this.selectedPages=[];
    if(evnt.checked)
    {
      for(var cn = 0 ; cn <  this.totalPages ;cn++ )
      {
        this.selectedPages.push(cn+1);
        this.pages[cn].status = true;
      }
    }
    else
    {
      for(var cn = 0 ; cn <  this.totalPages ;cn++ )
      {
        this.pages[cn].status = false; 
      }
      //for important
      this.importantPages = []
    }
    this.contentSandbox.pageSelectionDetails["selectedPages"] = this.selectedPages.length 
  }

  setSelecetdPages( pageSequence: any , pageSequenceArr: any) 
  {
    var  strSeq = pageSequence;
    var pagesArr = strSeq.split(',');
    for(var cn = 0 ; cn < pagesArr.length ; cn++)
    {
      var psgeNo =  pagesArr[cn];
      if(psgeNo.indexOf("-")>0)
      {
        var subPages = psgeNo.split('-');
        var startNo : number  = parseInt(subPages[0]);
        var endNo :  number  = parseInt(subPages[1]);
        for(var i = startNo ; i<= endNo ; i++)
        {
          pageSequenceArr.push(i);
        }
      }
      else
      {
        pageSequenceArr.push(parseInt(psgeNo));
      }
    }
  }
  onError(imageElement: any, description: any) {
    var targetImg = imageElement.target;
    var hostURL: string = this.contentSandbox.getHostUrl();
    var errorSrc: string = hostURL + '/ibase/CustomMenuImageServlet?fldValue=' + description + '&object=&objName=&ALT_FLD_VALUE=' + description + '&isOval=true';
    targetImg.src = errorSrc;
  }

  done()
  {
    let selectedPages = this.sortArray(this.selectedPages);
    let selectedPagesStr : String = "";
    selectedPagesStr = this.getSelectedPageSequence(selectedPages) ;
    //for important
    let importantPagesArr = this.sortArray( this.importantPages );
    let importantStr : String = "";
    importantStr = this.getSelectedPageSequence(importantPagesArr) ;

    //for important
   // update page_info   
    let selectedTemplate = this.contentSandbox.selectedTemplate;
    this.contentSandbox.updateSelectedTranObjects(selectedTemplate, selectedPages.length, selectedPagesStr, importantStr);
   
    console.log("ALL STORED  selectedTranObjS : ", this.contentSandbox.selectedTranObjects);  
  }

  sortArray(arrayElements : Array<any>) :Array<any>
  {
    arrayElements.sort(function(a, b) {
      return a-b;
    });
    return arrayElements;
  }
  
  getSelectedPageSequence ( selectedPages:Array<any> ) : String
  {

    var selectedPagesStr = "";
    for(var cn = 0 ; cn < selectedPages.length ; cn++)
    { 
      var temp = cn;
      //in case single page selectd
      // or last page
      // or diffrance between current and next page is greater than 1  
      if(selectedPages.length == 1 || selectedPages.length - 1 == cn || (selectedPages[cn+1]-selectedPages[cn]) > 1)
      {
        selectedPagesStr = selectedPagesStr +","+ selectedPages[cn]; 
        continue;
      }
      // Loop will execute upto last page
      // or diffrance between current and next page is 1   
      for( ; (temp < selectedPages.length - 1) && (selectedPages[temp+1]-selectedPages[temp]) ==1 ; temp++ );
      
      // if the loop execute more than 2
      if( temp - cn >=2 )
      {
        selectedPagesStr = selectedPagesStr +","+ selectedPages[cn] +"-"+selectedPages[temp]; 
        cn = temp;
      }
      // if loop execute once
      else
      {
        selectedPagesStr = selectedPagesStr +","+ selectedPages[cn] +","+selectedPages[temp];
        cn++; 
      }
    }
    if(selectedPagesStr.length>1)
    {
      selectedPagesStr = selectedPagesStr.substring(1);
    }
    return selectedPagesStr;
  }

   // For important
  removeImportantContainer(pageNav: any)
  {
    this.removePageFromImportant(pageNav.getAttribute("pageNumber"));

    if(pageNav.childNodes[3])
    {
      pageNav.removeChild(pageNav.childNodes[3]);
    }
  }
 
  removePageFromImportant(pageNumber:number)
  {
    var index = this.importantPages.indexOf(+pageNumber);
    if(index != -1)
    {
      this.importantPages.splice(index,1);
    }
  }
 
  addPageImportantContainer( pageNumber: any ):any
  {
    var pageImportantContainer = document.createElement("div");
    pageImportantContainer.setAttribute("class", "important-container");
    pageImportantContainer.innerHTML = ` <span class="important-span"> Important</span> `; 
    
    var pageImportantIcon = document.createElement("span");
    pageImportantIcon.innerHTML="grade";
    
    if(this.importantPages.indexOf( pageNumber) != -1 )
    {
      pageImportantIcon.setAttribute("class","material-icons important-icon important-icon-selected");
    }
    else
    {
      pageImportantIcon.setAttribute("class", "material-icons important-icon");
    }
    // var self = this;
    this.addPageImportantClickHandler(pageImportantContainer, pageImportantIcon, pageNumber);
    pageImportantContainer.appendChild(pageImportantIcon);
     
    return pageImportantContainer;
  }

  addPageImportantClickHandler(pageImportantContainer: any, pageImportantIcon: any, pageNumber: any)
  {
    var self = this;
    pageImportantContainer.onclick = function(){
      let pageImportantIconClasses = pageImportantIcon.getAttribute("class");
 
      if(pageImportantIconClasses.indexOf("important-icon-selected")== -1)
      {
        if(self.importantPages.indexOf(pageNumber) ==-1)
        {
          self.importantPages.push(pageNumber);
        }
        pageImportantIcon.setAttribute("style", "color: #ff720d;");
        pageImportantIcon.setAttribute("class","material-icons important-icon important-icon-selected");
      }
      else
      {
        self.removePageFromImportant(pageNumber);
        pageImportantIcon.setAttribute("class", "material-icons important-icon");
        pageImportantIcon.setAttribute("style", "color: #fff;");
      }
    };
  }
}
