import jsPDF from 'jspdf';
import 'jspdf-autotable';
import { applyPlugin } from 'jspdf-autotable';
import { mapValues } from 'lodash';
import { Column } from './models';
applyPlugin(jsPDF);

type ExtendedJsPDF = jsPDF & { autoTable?: any; lastAutoTable?: any; autoTableSetDefaults?: any };

export class TableBuilder {
  currentY = 10;

  constructor(private doc: ExtendedJsPDF) {}

  public addTable(table: Table) {
    const { columns, rows } = table;
    const data = this.formatData(rows);
    const headers = this.buildHeaders(columns);
    this.doc.autoTable({
      columns: headers,
      body: data,
    });
    this.currentY = this.doc.lastAutoTable.finalY + 10;
  }

  private formatData(rows: Row[]) {
    return rows.map((row) => mapValues(row, (val) => `${val}`));
  }

  private buildHeaders(columns: Column[]): PDFColumn[] {
    const headers = columns.map(
      (col) =>
        ({
          header: col.header,
          dataKey: col.key,
          //   width: col.width,
          //   align: 'center',
          //   padding: 0,
        } as PDFColumn)
    );
    return headers;
  }
}
type Row = Record<string, any>;
interface PDFColumn {
  header: string;
  dataKey: string;
  columnStyles?: { [key: string]: { halign: 'center' } };
}

export interface Table {
  columns: Column[];
  rows: Row[];
}
