import { Component, OnInit, Input,ViewChild,  TemplateRef,
  ViewContainerRef, Output, EventEmitter, NgZone} from '@angular/core';
import {
  Overlay,
  OverlayConfig
} from '@angular/cdk/overlay';
import {
  TemplatePortal
} from '@angular/cdk/portal';
import { BackgroundJobStatusService } from "./background-job-status.service";
@Component({
  selector: 'background-job-status',
  templateUrl:'./background-job-status.component.html',
  styleUrls: ['./background-job-status.component.css']
})
export class BackgroundJobStatusComponent implements OnInit {
  
  @Input('data') dashboardData: any;
  @Input('objName') objName: any;
  //@Input('elWidth') elWidth;
  url : any;
  overlayRef: any;
  clientWidth: any;
  batchId: any;
  docId:any;
  widthdiv: any;
  @ViewChild('dynamicTemp') dynamicTemp: any;
  //@ViewChild('portal') templateport: FlexmonsterPivot;
  @ViewChild( 'portal' ) templatePortal: TemplateRef<any> | any;
  divHeight:any;
  usDivHeight:any;
  config = new OverlayConfig(); 
  /*Changed By Vikas Lagad on 03-Oct-2019  [Changes for export file to zip]Start*/
  usDivWidth:any;
  @Output() onClose: EventEmitter<any> = new EventEmitter();
  @Input('fromExportToZip') fromExportToZip: any = false;
  overlayDivHeight: number = 400; // for Sun only
  /*Changed By Vikas Lagad on 03-Oct-2019  [Changes for export file to zip]End*/

  constructor(public overlay: Overlay,
  private viewContainerRef: ViewContainerRef,public zone: NgZone,private backgroundjobstatusService:BackgroundJobStatusService) { }
  ngOnInit() {
  	  /*Changed by Sainath T. on 07-OCT-2019*/ 
      try 
      {
        if(this.fromExportToZip)
        {
          //Changed by Sainath T. on 04-03-2020[for head release] - end
          //this.usDivHeight = (window.innerHeight) - 143;//For JBOSS Sun
          this.usDivHeight = (window.innerHeight) - 80;//For Head
          this.usDivWidth = (window.innerWidth);
        }
        else
        {
          this.usDivHeight = (window.innerHeight) - 262; 
        }      
      } catch
      {
         console.log('Exception while setting usDivHeigh'); 
      }
  }
  ngOnChanges()
  {
    //console.log("ngOnChnages in bckground job", this.dashboardData);
  }
  /*Changed by Sainath T. on 07-OCT-2019*/
  
  /*Added by vikas l. on 03-OCT-2019*/
  /*Added by Saianth T. on 01-NOV-2019[passed object name to save file with it]*/
  onclick(batchID: any, objName:string, isDone?:boolean)
  {
    console.log('Inside On Click....',batchID,isDone);
    if( isDone && this.fromExportToZip) 
    {
      this.getDownloadZip(batchID, objName);
    } 
    else 
    {
      console.log("on click working",batchID);
      this.batchId=batchID;
      console.log("id=",this.batchId);
      setTimeout(()=>
      {
        this.createOverlay();   
      },1);
    }
  }
  /*Added by vikas l. on 03-OCT-2019*/

  onclickView()
  {
    this.dynamicTemp.ngOnInit();
  }
  createOverlay() 
  {
  	//Changed by Sainath T. on 04-OCT-2019 [To Set diff. position for diff. components]-Start
    console.log("Creating overlay ::");
    let position : any;
    if (this.fromExportToZip )
    {
      try
      {
        position = parent.document.getElementsByClassName( "frameStyle" )[0].getBoundingClientRect();
      }
      catch
      {
        // position = document.getElementById("dashboardDiv").parentElement.getBoundingClientRect(); 
        position = document.getElementById("dashboardDiv")?.parentElement?.getBoundingClientRect(); 
      }
      console.log('position>>', position);
    }
    else
    {
      //Changed by Sainath T. on 30-AUG-2019 [Changes id from 'dashboard_backgroundJobStatus' to 'background_job_status']
      try{
        // position = document.getElementById("background_job_status").parentElement.getBoundingClientRect();
        position = document.getElementById("background_job_status")?.parentElement?.getBoundingClientRect();
      }
      catch
      {
        // position = document.getElementById("dashboard_backgroundJobStatus").parentElement.getBoundingClientRect();
        position = document.getElementById("dashboard_backgroundJobStatus")?.parentElement?.getBoundingClientRect(); 
      }
      
    }
    this.config.hasBackdrop = true;
    this.setPosition(position);
  	//Changed by Sainath T. on 04-OCT-2019 [To Set diff. position for diff. components]-End
  }
  closeOverlay()
  {
    this.onClose.emit();
    this.overlayRef.dispose();
  }

  setPosition( position : any)
  {
    var width = position.width + 7;
    var top = position.top;
    var height = position.height; //+34
    var left = position.left;
    var bottom = position.bottom;
    var right = position.right;
    //Added by Sainath T. on 09-OCT-2019 -Start
    this.overlayDivHeight = this.fromExportToZip ? (height - 83) : (height - 18); // For Sun 83
    this.divHeight = this.fromExportToZip ? (height - 184) : (height - 121);
    //Added by Sainath T. on 09-OCT-2019 -End
    console.log('position:h:w:t:l:r:b:',height,'',width,'',top,'',left,'',right,'',bottom);
    console.log( 'config & templatePortals ', this.config, this.templatePortal );
    this.config.positionStrategy = this.overlay.position()
      .global()
      .width( width )
      .top( top )
      .bottom(bottom)        
      .height( height )
      .left(left)
      .right(right);
    //Added by Sainath T. on 04-OCT-2019 -Start
    const templatePortal = new TemplatePortal(
    this.templatePortal,
    this.viewContainerRef
    );
    this.overlayRef = this.overlay.create( this.config );
    this.overlayRef.attach( templatePortal );  
    //Added by Sainath T. on 04-OCT-2019 -End
  }

  getDownloadStatus(batchId: any)
  {
    //<!-- added  by sadique shaikh 29-1-2019[to download xls file]  -->
   // this.dynamicTemp.ngOnInit();
    var docType ="xls";
    var url;
    var docId;
    console.log("download batch id"+batchId)
  // this.url = "/ibase/UploadTemplateServlet?action=DOWNLOAD_FILE&BATCH_ID="+batchId;
    this.backgroundjobstatusService.getBackgroundjobDocId(this.batchId).subscribe(
      data=>{
        docId = data
        console.log('Doc Id===',data);
        if(docId == "" || docId == "undefined" || docId == null)
        {
          alert("No attachment found against selected template");                                        
        }
        else
        { if(docType != null)
          {   
            docType = docType.toLowerCase();                                                                     
            url = "/ibase/WebITMDocumentHandlerServlet?OBJ_NAME=I-BL&REF_ID="+batchId+"&ACTION=GET_DOCUMENT&CLIENT=WEB1&DOC_ID=" + docId + "&DOC_TYPE=" + docType;
            window.open(url);                                                                                                                                                                                 
          }   
        }
      });
    }

	/* Added By Vikas Lagad on 03-Oct-2019  to download zip file[Start]*/
    getDownloadZip(batchId: any, objName:string)
    {
      var fileName = '';
      var userCode = this.getStorageItem( "userName" );
      var paramMap: any = {};
      var paramString = "";
      paramMap["ACTION"] = 'DOWNLOAD_FILE';
      paramMap["OBJ_NAME"] = objName;
      paramMap["JOB_ID"] = batchId;
      fileName =  userCode + '_'+ this.objName + '_' + batchId + '.zip';
      console.log('File name  .. ',fileName);
      paramString = this.backgroundjobstatusService.getEncodedParamString(paramMap);
      this.backgroundjobstatusService.downloadZip(paramString,fileName);
    }

    getStorageItem(key: any): string {
      return localStorage.getItem(key) as any;
    }
    /* Added By Vikas Lagad on 03-Oct-2019  to download zip file[End]*/
}
/*Added by Sainath T on 03-OCT-2019*/
export function downloadURI(uri: any, name: any) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  /* delete link; */
}
 /*Added by Sainath T on 03-OCT-2019*/
