/** This is a service to convert json data into xsl sheet
 *
 * @param jsondata
 * @param xsl filename
 *
 * Added by Sonam K.
 */

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

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable()
export class ExcelService {

  constructor() { }
  public exportAsExcelFile(jsonData: any[], excelFileName: string): void {
    console.log('Inside service ::exportAsExcelFile()');

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData); //convert json to xsl
    console.log('worksheet',worksheet);

    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    //const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    console.log('in service :: saveAsExcelFile()');
    const data: Blob = new Blob([buffer], {
      type: EXCEL_TYPE
    });
    FileSaver.saveAs(data, fileName +  EXCEL_EXTENSION);
  }

}