"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadFile = void 0;
const follow_redirects_1 = require("follow-redirects");
const fs_1 = __importDefault(require("fs"));
const getTempFilepath_1 = require("./getTempFilepath");
const downloadFile = (url) => {
    return new Promise((resolve, reject) => {
        const tempFilepath = (0, getTempFilepath_1.getTempFilepath)();
        const protocol = url.startsWith('https') ? follow_redirects_1.https : follow_redirects_1.http;
        const writeStream = fs_1.default.createWriteStream(tempFilepath);
        const request = protocol.get(url, (response) => {
            if (typeof response.statusCode === 'undefined' || response.statusCode >= 400) {
                reject(new Error(`Cannot download file: ${url}`));
                return;
            }
            response.on('error', (error) => {
                writeStream.close();
                reject(error);
            });
            response.on('end', () => {
                writeStream.on('finish', () => {
                    writeStream.close();
                    resolve(tempFilepath);
                });
            });
            response.pipe(writeStream);
        });
        request.on('error', (error) => {
            writeStream.close();
            reject(error);
        });
    });
};
exports.downloadFile = downloadFile;
