import { Injectable } from '@angular/core';
import * as XLSX from "xlsx";

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

  downloadJSON(input: Object[], fileName: string = 'data') {
    const dataStr = JSON.stringify(input);
    const blob = new Blob([dataStr], { type: 'application/json' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');

    link.href = url;
    link.download = fileName + '.json';
    link.click();
  }

  downloadCSV(input: Object[], columns: string[], fileName: string = 'data') {
    const header = columns.join(',') + '\n';

    let csvData = input.map(row =>
      input.map(row => Object.values(row).join(',')).join('\n')
    ).join('\n');
    csvData = header + csvData;

    const blob = new Blob([csvData], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');

    link.href = url;
    link.download = fileName + '.csv';
    link.click();
  }

  downloadXLSX(input: Object[], fileName: string = 'data') {
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(input);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, ws, 'Main Sheet');
    XLSX.writeFile(wb, fileName + '.xlsx');
  }

}
