import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

@Injectable({
  providedIn: 'root'
})
export class ExcelExportService {

  constructor() { }
  fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
  fileExtension = '.xlsx';

  public exportExcel(jsonData: any, fileName: string): void {

    console.log(jsonData)
    if(jsonData instanceof Array ){



    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData);
    const wb: XLSX.WorkBook = { Sheets: { 'data': ws }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    this.saveExcelFile(excelBuffer, fileName);
     
    }else{
      let wb = XLSX.utils.table_to_book(jsonData);
      console.log(wb)
      const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      this.saveExcelFile(excelBuffer, fileName);
     // XLSX.writeFile(wb, fileName + this.fileExtension);
    }


      /* table id is passed over here */   
    //   console.log(jsonData, typeof(jsonData),jsonData.getElementsByTagName('mat-icon'))
    //   let temp = jsonData.getElementsByClassName('mat-icon')
    //   temp.innerHTML = ''
    //   console.log(temp)
    // //  jsonData.removeChild()
    //   const ws: XLSX.WorkSheet =XLSX.utils.table_to_sheet(jsonData);

    //   /* generate workbook and add the worksheet */
    //   const wb: XLSX.WorkBook = XLSX.utils.book_new();
    //   XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    //   const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    //   this.saveExcelFile(excelBuffer, fileName);
      // /* save to file */
      // XLSX.writeFile(wb, this.fileName);
  }

  private saveExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {type: this.fileType});
    FileSaver.saveAs(data, fileName + this.fileExtension);
  }
}
