import { saveAs } from 'file-saver';
import { humanize } from '@iqser/common-ui/lib/utils';

function toCSVContent(lines: any[], keys: string[]) {
    return lines
        .map(line => {
            const escapedValues: any[] = [];
            for (const key of keys) {
                escapedValues.push('"' + (line[key] !== null && line[key] !== undefined ? `${line[key]}`.replace('"', '""') : '') + '"');
            }

            return escapedValues.join(',');
        })
        .join('\n');
}

function camelCaseToSnakeCase(item: string) {
    return item.replace(/[\w]([A-Z])/g, m => m[0] + '_' + m[1]).toLowerCase();
}

export function saveAsCSV(fileName: string, objects: readonly any[], fields: string[], mapper: (any) => any = (input: any) => input) {
    const headerLine = fields.map(f => '"' + humanize(camelCaseToSnakeCase(f)) + '"').join(',') + '\n';
    const csvContent = toCSVContent(objects.map(mapper), fields);

    const blob = new Blob([headerLine + csvContent], {
        type: 'text/csv;charset=utf-8',
    });

    saveAs(blob, fileName);
}
