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

/**
 * Given a URL, download the file at that URL as a file with the given filename.
 * Especially useful when used with data URLs (see https://en.wikipedia.org/wiki/Data_URI_scheme)
 * @param {string} url
 * @param {string} [filename] what should the file be called? Should include the desired extension.
 */
export function downloadUrlAsFile(url, filename = "file") {
    assert.isString(url, 'url');
    assert.isString(filename, 'filename');

    const elem = document.createElement('a');
    elem.href = url;
    elem.download = filename;

    // only elements on the dom are clickable, so we add it
    document.body.appendChild(elem);
    elem.click();
    document.body.removeChild(elem);
}

