import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import {texttelescopeservice} from './texttelescope.service';
import { DatePipe } from '@angular/common';
//import * as XLSX from 'xlsx';
import * as ExcelJS from 'exceljs';
import { saveAs } from "file-saver";

@Component({
  selector: 'app-texttelescope',
  templateUrl: './texttelescope.component.html',
  styleUrls: ['./texttelescope.component.css']
})
export class TexttelescopeComponent implements OnInit {
  lob: any[] = [];
  today: Date = new Date(); // Get today's date
  //selectedDateRange: Date[];
  selectedLob: number;
  startdate:any;
  enddate:any;
  downloadData = [];
  constructor(
    private datepipe :DatePipe,
    private toastr: ToastrService,
    private texttelescopeservice: texttelescopeservice
  ) { 
    this.today.setHours(0, 0, 0, 0);
  }

  ngOnInit(): void {
    this.loadLobName();
    //this.selectedDateRange = [new Date(), new Date(Date.now() + 86400000)];
  }
  loadLobName() {
    this.lob = [];
    this.texttelescopeservice.GetLobAll().subscribe(res => {
      debugger;
      this.lob = JSON.parse(res);
    }, error => { this.toastr.error('Error while getting LOB data'); });
  }
  onDateRangeSelection(value: Date[]) {
    this.startdate = this.datepipe.transform(value[0], 'dd-MMM-yyyy');
    this.enddate = this.datepipe.transform(value[1], 'dd-MMM-yyyy');
  }
  
  exportData() {
    const exportRecord = [];
    var sDate = this.startdate;
    var eDate = this.enddate;
    sDate += " 00:00:00";
    eDate += " 23:59:59";
    exportRecord.push({
      startDate:  sDate,
      endDate: eDate,
      lobId: Number(this.selectedLob)});  
      debugger; 
    this.texttelescopeservice.getDataForDownload(exportRecord[0]).subscribe(res => {
      if(res.body[0] != null) {
        this.downloadData = res.body[0];
        this.downloadExcel();
      } else {
        this.toastr.error('Data not available for selected date range');
      }
      
    }, error => { this.toastr.error('Error while getting data'); });
  }  
  downloadExcel() {
    try {
      const jsonData = JSON.parse(this.downloadData.toString());

      if (Array.isArray(jsonData)) {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('Sheet1');

        // Add headers
        const headers = Object.keys(jsonData[0]);
        //worksheet.addRow(headers).font = { bold: true };
        const headerRow = worksheet.addRow(headers);
        headerRow.eachCell((cell) => {
          if (cell.value) {
            cell.font = { bold: true, color: { argb: 'FFFFFF' } };
            cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '2b4c81' } };
          }
        });
        worksheet.columns.forEach((column) => {
          column.width = 20; // Set column width
        });

        // Add data
        jsonData.forEach((row) => worksheet.addRow(Object.values(row)));

        // Simulate borders using additional rows       
        worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
          row.eachCell((cell) => {
            cell.border = { 
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
           };
          });
        });
        // Save the workbook to a file
        //workbook.xlsx.writeFile('data.xlsx');
        workbook.xlsx.writeBuffer().then((buffer) => {
          saveAs(
            new Blob([buffer], { type: "application/octet-stream" }),
            "Telescope("+this.startdate +" to "+this.enddate+").xlsx"
          );
        })
        this.toastr.success('Excel downloaded successfully');
      } else {
        this.toastr.error('Error: jsonData is not an array. Contact Administator');
      }
    } catch (error) {
      console.error('Error in downloading excel', error);
    }
  }

  /*downloadExcel() {
    
    try {
      // Parse the main JSON string into a JavaScript object
      const jsonData = JSON.parse(this.downloadData);

      // Ensure jsonData is an array
      if (Array.isArray(jsonData)) {
        // Convert the data to a worksheet
        const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData);

        // Apply styles to all rows
        const range = XLSX.utils.decode_range(ws['!ref']);
        for (let row = range.s.r; row <= range.e.r; ++row) {
          const startCell = XLSX.utils.encode_cell({ r: row, c: range.s.c });
          const endCell = XLSX.utils.encode_cell({ r: row, c: range.e.c });
          XLSX.utils.sheet_set_range_style(ws, `${startCell}:${endCell}`, {
            bottom: { style: 'thin' }
          });
        }

        // Create a workbook and add the worksheet
        const wb: XLSX.WorkBook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

        // Save the workbook to a file
        XLSX.writeFile(wb, 'Telescope('+this.startdate +' to '+this.enddate+').xlsx');
        console.log('Data downloaded successfully');
      } else {
        console.error('Error: jsonData is not an array');
      }
    } catch (error) {
      console.error('Error parsing JSON:', error);
    }
  }*/
}
