import { downloadUrlAsFile } from "./downloadUrlAsFile.js";

/**
 * Utility method for downloading data as a file
 * @param {ArrayBuffer|Uint8Array|Array|Blob|string} data
 * @param {string} [filename]
 * @param {string} [type]
 */
export function downloadAsFile(data, filename, type = 'text/json') {

    let blobContent;

    if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
        //raw binary data
        blobContent = [data];
    } else if (data instanceof Array) {
        //already an array
        blobContent = data;
    } else if (data instanceof Blob) {
        //already a blob
        blobContent = [data];
    } else if (typeof data === "string") {
        blobContent = [data];
    } else {
        blobContent = [data]
    }

    const blob = new Blob(blobContent, { type });

    downloadUrlAsFile(window.URL.createObjectURL(blob), filename);
}
