"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.webFile = void 0;
const APINotImplementedError_1 = require("../../../../exception/APINotImplementedError");
function webFile(window, opt) {
    const { document } = window;
    const isSaveFilePickerSupported = () => {
        // @ts-ignore
        return !!window.showSaveFilePicker;
    };
    const isOpenFilePickerSupported = () => {
        // @ts-ignore
        return !!window.showOpenFilePicker;
    };
    function showSaveFilePicker(opt) {
        if (isSaveFilePickerSupported()) {
            // @ts-ignore
            return window.showSaveFilePicker(opt);
        }
        else {
            throw new APINotImplementedError_1.APINotSupportedError('File System');
        }
    }
    function showOpenFilePicker(opt) {
        if (isOpenFilePickerSupported()) {
            // @ts-ignore
            return window.showOpenFilePicker(opt);
        }
        else {
            throw new APINotImplementedError_1.APINotSupportedError('File System');
        }
    }
    function fallbackShowOpenFilePicker(opt) {
        return new Promise((resolve, reject) => {
            var _a;
            const input = window.document.createElement('input');
            input.type = 'file';
            input.hidden = true;
            input.multiple = opt.multiple || false;
            input.accept = (_a = opt.accept) !== null && _a !== void 0 ? _a : '*/*';
            window.document.body.appendChild(input);
            input.onchange = () => __awaiter(this, void 0, void 0, function* () {
                const files = input.files;
                if (!files) {
                    reject(new Error('No files selected'));
                    return;
                }
                const final_files = [];
                for (let i = 0; i < files.length; i++) {
                    const file = files.item(i);
                    final_files.push(file);
                }
                resolve(final_files);
            });
            input.click();
            window.document.body.removeChild(input);
        });
    }
    const downloadText = ({ name, mimetype: mimeType, charset, text, }) => __awaiter(this, void 0, void 0, function* () {
        const url = `data:${mimeType};charset=${charset},${encodeURIComponent(text)}`;
        return downloadURL({ name, url });
    });
    const testGet = (url) => __awaiter(this, void 0, void 0, function* () {
        try {
            yield fetch(url);
            return true;
        }
        catch (err) {
            // console.log(err)
            return false;
        }
    });
    const downloadURL = ({ name, url }) => __awaiter(this, void 0, void 0, function* () {
        if (url.startsWith('http://') || url.startsWith('https://')) {
            const accessible = yield testGet(url);
            if (!accessible) {
                throw new Error('URL is not accessible due to CORS policy');
            }
        }
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.download = name;
        a.href = url;
        a.click();
        document.body.removeChild(a);
    });
    const file = {
        showSaveFilePicker,
        isSaveFilePickerSupported,
        isOpenFilePickerSupported,
        showOpenFilePicker,
        fallbackShowOpenFilePicker,
        downloadURL,
        downloadText,
    };
    return file;
}
exports.webFile = webFile;
//# sourceMappingURL=file.js.map