import { createFileWithPath, download, downloadTable, FileCollection, FileMimeType } from '@data-wrangling-components/utilities';
import { useCallback, useState } from 'react';
export function useDownloadWorkflow(workflow) {
    return useCallback(()=>{
        if (workflow != null) {
            const blob = toBlobJson(workflow.toJsonObject());
            download('worfklow.json', FileMimeType.json, blob);
        }
    }, [
        workflow
    ]);
}
export function useDownloadCsv(tables) {
    return useCallback(()=>{
        for (const table of tables){
            if (table?.table) {
                downloadTable(table.table, tableName(table.id));
            }
        }
    }, [
        tables
    ]);
}
export function useDownloadZip(workflow, tables, outputTables) {
    const [fileCollection] = useState(new FileCollection());
    return useCallback(async ()=>{
        fileCollection.clear();
        const input = [];
        const output = [];
        for (const outputTable of outputTables){
            if (outputTable?.table) {
                const file = tableFile(outputTable, outputTable.id);
                if (file) {
                    await fileCollection.add(file);
                    output.push(file.name);
                }
            }
        }
        if (tables.length) {
            const files = tables.map((table)=>tableFile(table)).filter((f)=>f != null);
            if (files.length) {
                await fileCollection.add(files);
                tables.forEach((table)=>{
                    input.push(table.id);
                });
            }
        }
        if (input.length || output.length) {
            const blob = toBlobJson({
                input,
                output
            });
            const file1 = createFileWithPath(blob, {
                name: 'metadata.json'
            });
            await fileCollection.add(file1);
        }
        if (workflow) {
            const blob1 = toBlobJson(workflow.toJsonObject());
            const file2 = createFileWithPath(blob1, {
                name: 'workflow.json'
            });
            await fileCollection.add(file2);
        }
        if (fileCollection.list().length) {
            await fileCollection.toZip('dwc-project');
        }
    }, [
        fileCollection,
        workflow,
        tables,
        outputTables
    ]);
}
function toBlobJson(serializable) {
    return new Blob([
        JSON.stringify(serializable, null, 4)
    ]);
}
function tableName(name) {
    return name.endsWith('.csv') ? name : `${name}.csv`;
}
function tableFile(t, name) {
    return t.table ? createFileWithPath(new Blob([
        t.table.toCSV()
    ]), {
        name: tableName(name || t.id)
    }) : null;
}
