"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchDownloadFile = fetchDownloadFile;
const HubError_1 = require("../HubError");
const canUseExportImageFlow_1 = require("./_internal/canUseExportImageFlow");
const canUseHubDownloadApi_1 = require("./canUseHubDownloadApi");
const getDownloadFormats_1 = require("./getDownloadFormats");
const fetchHubApiDownloadFile_1 = require("./_internal/file-url-fetchers/fetchHubApiDownloadFile");
const fetchExportImageDownloadFile_1 = require("./_internal/file-url-fetchers/fetchExportImageDownloadFile");
/**
 * Fetches a download file URL for the given entity and format.
 * @param options options to refine / filter the results of the fetchDownloadFile operation
 * @returns a promise that resolves with a download file url or blob
 * @throws {ArcgisHubDownloadError} if the download file URL cannot be fetched for a well-known reason
 */
async function fetchDownloadFile(options) {
    // Make sure that format requested has been enabled for the entity
    validateFormat(options);
    // If the pollInterval is not set, default to 3 seconds
    const withPollInterval = options.pollInterval == null ? Object.assign(Object.assign({}, options), { pollInterval: 3000 }) : options;
    let fetchingFn;
    if ((0, canUseHubDownloadApi_1.canUseHubDownloadApi)(withPollInterval.entity, withPollInterval.context)) {
        fetchingFn = fetchHubApiDownloadFile_1.fetchHubApiDownloadFile;
    }
    else if ((0, canUseExportImageFlow_1.canUseExportImageFlow)(withPollInterval.entity)) {
        fetchingFn = fetchExportImageDownloadFile_1.fetchExportImageDownloadFile;
    }
    else {
        throw new HubError_1.default("fetchDownloadFile", "Downloads are not supported for this item in this environment");
    }
    return fetchingFn(withPollInterval);
}
/**
 * Validates the format requested is enabled for the entity
 * @param options options for the fetchDownloadFile operation
 * @throws {HubError} if the format requested is not enabled for the entity
 */
function validateFormat(options) {
    const { entity, context, format } = options;
    const validServerFormats = (0, getDownloadFormats_1.getDownloadFormats)({
        entity,
        context,
    })
        .filter((f) => f.type === "dynamic")
        .map((f) => f.format);
    if (!validServerFormats.includes(format)) {
        throw new HubError_1.default("fetchDownloadFile", `The following format is not enabled for the entity: ${format}`);
    }
}
//# sourceMappingURL=fetchDownloadFile.js.map