import { ModalController } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';

type AOA = any[][];
const ZOOM_STEP: number = 0.25;
const DEFAULT_ZOOM: number = 1;

@Component({
  selector: 'app-work-list-attach-view',
  templateUrl: './work-list-attach-view.component.html',
  styleUrls: ['./work-list-attach-view.component.scss'],
})
export class WorkListAttachViewComponent implements OnInit {

  displayPdf: string = "";
  displayImage: string = "";
  TypeData: string = "";
  displayData: string = "";
  decodedString: any;
  displayxlsx: string = "";
  public pdfZoom: number = DEFAULT_ZOOM;
  sheetNameList: any = [];
  sheetDataList: any = [];

  data: any[][];//[[1,2,3],[4,5,6]];

  constructor(private cs: CommonService, private ts: TranslatorService, private modalCtrl: ModalController) {
    this.displayData = this.cs.sharedService.getSharedData('WorkListAttachViewPage', false).displayData;
    this.TypeData = this.cs.sharedService.getSharedData('WorkListAttachViewPage', false).TypeData;

    if (this.TypeData == "png" || this.TypeData == "jpeg" || this.TypeData == "jpg" || this.TypeData == "PNG" || this.TypeData == "JPEG" || this.TypeData == "JPG") {
      this.displayImage = 'data:image/' + this.TypeData + ';base64,' + this.displayData;
    }
    else if (this.TypeData == "pdf" || this.TypeData == "PDF") {
      this.displayPdf = 'data:application/octet-stream;base64,' + this.displayData;
    }
    else if (this.TypeData == "txt") {
      //
      this.decodedString = atob(this.displayData);
      // console.log("..."+ this.decodedString);
    }
    else if (this.TypeData == "xlx" || this.TypeData == "xlsx") {
      this.displayxlsx = this.displayData;
      var base64 = this.displayxlsx;//.split(";base64,")
      var binary = "";
      var raw = window.atob(base64);
      var rawLength = raw.length;
      var array = new Uint8Array(new ArrayBuffer(rawLength));

      for (let i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i);
      }

      var length = array.byteLength;
      for (let i = 0; i < length; i++) {
        binary += String.fromCharCode(array[i]);
      }
      const wb: XLSX.WorkBook = XLSX.read(binary, { type: 'binary', cellDates: true });

      /* grab first sheet */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];
      //   if(ws["!type"]=="chart")
      //   {
      //     alert("chart");
      // }
      // else alert("able");

      this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));

      //  const wsname1: string = wb.SheetNames[1];
      //  const ws1: XLSX.WorkSheet = wb.Sheets[wsname];
      //  console.log("wsname..."+wsname);
      //  console.log("ws..."+ws);
      /* save data */
      //  this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
      //  this.data = <AOA>(XLSX.utils.sheet_to_json(ws1, {header: 1}));


      for (let i = 0; i < wb.SheetNames.length; ++i) {
        const sheetName = wb.SheetNames[i];
        const ws: XLSX.WorkSheet = wb.Sheets[sheetName];
        this.sheetNameList.push({ id: i, sheetName: sheetName });
        this.sheetDataList.push({ id: i, sheetData: ws });
      }
    }//if file == xlx/s
    else {
      let msg: string = "";
      msg = this.ts.trPK("general", "notSupportFile");
      this.cs.presentAlert(msg);
    }
  }

  ngOnInit() { }

  public zoomIn() {
    this.pdfZoom += ZOOM_STEP;
  }

  public zoomOut() {
    if (this.pdfZoom > DEFAULT_ZOOM) {
      this.pdfZoom -= ZOOM_STEP;
    }
  }

  public resetZoom() {
    this.pdfZoom = DEFAULT_ZOOM;
  }

  onClose(): void {
    this.modalCtrl.dismiss();
  }

  base64ToByteArray(base64String) {
    try {
      var sliceSize = 1024;
      var byteCharacters = atob(base64String);
      var bytesLength = byteCharacters.length;
      var slicesCount = Math.ceil(bytesLength / sliceSize);
      var byteArrays = new Array(slicesCount);

      for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
          bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
      }
      return byteArrays;
    } catch (e) {
      //console.log("Couldn't convert to byte array: " + e);
      return undefined;
    }
  }


  openSheet(obj) {
    this.data = <AOA>(XLSX.utils.sheet_to_json(this.sheetDataList[obj.id].sheetData, { header: 1 }));
  }

}
