import { fetchPdf } from '../utils';
import { default as fileDownload } from 'js-file-download';
function csvQuote(value) {
    if (!value)
        return '';
    return (value.indexOf(',') !== -1) ?
        `"${value.replace(/"/g, '""')}"` : value;
}
export class TableExportController {
    async create(options) {
        let tableSelector = 'gl-table' +
            ((options.tableId) ? `#${options.tableId}` : '');
        let table = (options.table) ? options.table :
            document.querySelector(tableSelector);
        let features = (options.features) ? options.features :
            await table.getSortedFeatures();
        let columns = (options.columns) ? options.columns :
            Array.from(table.querySelectorAll('gl-table-column'));
        if (options.format === 'csv')
            this.exportCsv(table, features, columns, options);
        if (options.format === 'pdf')
            this.exportPdf(table, features, columns, options);
    }
    async exportCsv(table, features, columns, options) {
        let csv = await this.createCsvDoc(table, features, columns);
        fileDownload(csv, this.getFilename(options), 'text/csv');
    }
    async exportPdf(table, features, columns, options) {
        let dd = await this.createDocDef(table, features, columns, options);
        if (options.url) {
            fetchPdf(options.url, options.filename, dd);
        }
        else {
            pdfMake.createPdf(dd).download(this.getFilename(options));
        }
    }
    getFilename(options) {
        if (options.filename)
            return options.filename;
        if (!options.pageTitle)
            return `table.${options.format}`;
        return `${options.pageTitle.toLowerCase()
            .replace(/[^a-z0-9]+/g, '_')}.${options.format}`;
    }
    async createCsvDoc(table, features, columns) {
        let filteredColumns = columns.filter(col => col.visible && col.csv);
        let headerRow = filteredColumns.map((col) => csvQuote(col.label));
        let featureRows = (await Promise.all(features.map((feature) => this.getTableRow(table, feature, filteredColumns, 'text'))))
            .map((row) => row.map((cell) => csvQuote(cell)));
        return [headerRow, ...featureRows]
            .map((row) => row.join(','))
            .join('\n');
    }
    getTableRow(table, feature, columns, type = 'pdf') {
        return Promise.all(columns.map((column) => table.getCellContents(feature, column, type)));
    }
    async createDocDef(table, features, columns, options) {
        let filteredColumns = columns.filter(col => col.visible && col.pdf);
        let header = filteredColumns.map((col) => {
            return { text: col.label, style: 'th' };
        });
        let featureRows = await Promise.all(features.map((feature) => this.getTableRow(table, feature, filteredColumns)));
        let formattedRows = featureRows.map((row, i) => {
            return row.map((cell) => {
                return {
                    text: cell,
                    style: (i % 2 == 0) ? 'td-zebra' : 'td'
                };
            });
        });
        let docDef = {
            template: 'landscape',
            info: {},
            pageOrientation: options.pageOrientation,
            content: [
                {
                    table: {
                        headerRows: 1,
                        body: [header, ...formattedRows]
                    }
                },
            ]
        };
        if (options.pageSubtitle)
            docDef['content'].unshift({ text: options.pageSubtitle, style: 'h2', alignment: 'center' });
        if (options.pageTitle) {
            docDef['info']['title'] = options.pageTitle;
            docDef['content'].unshift({ text: options.pageTitle, style: 'h1-title', alignment: 'center' });
        }
        if (options.author)
            docDef['info']['author'] = options.author;
        console.log(docDef);
        return docDef;
    }
    static get is() { return "gl-table-export-controller"; }
    static get methods() { return {
        "create": {
            "complexType": {
                "signature": "(options: TableExportOptions) => Promise<void>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    },
                    "TableExportOptions": {
                        "location": "import",
                        "path": "./interfaces"
                    },
                    "HTMLGlTableElement": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "",
                "tags": []
            }
        }
    }; }
}
