import fs from 'fs';
import { get } from 'https';
import path from 'path';
import { inspect } from 'util';
import { logger } from './utils.mjs';
import { packageJson } from '../lib/index.mjs';
const downloadFile = (url, filename) => {
    return new Promise((resolve, reject) => {
        logger.verboseInfo(`Downloading file: ${url}`);
        get(url, response => {
            if (response.statusCode !== 200) {
                reject(new Error(`Error downloading ${url}: ${response.statusCode} - ${response.statusMessage}`));
                return;
            }
            logger.debug(`Creating file: ${path.join(filename)}`);
            const fileStream = fs.createWriteStream(`${filename}`);
            fileStream.on('finish', () => fileStream.close());
            fileStream.on('close', () => resolve(filename));
            response.pipe(fileStream);
        }).on('error', e => {
            reject(e);
        });
    });
};
export const downloadJdlFile = async (jdlFile, { skipSampleRepository } = {}) => {
    let url;
    try {
        const urlObject = new URL(jdlFile);
        url = jdlFile;
        jdlFile = path.basename(urlObject.pathname);
    }
    catch (_error) {
        if (skipSampleRepository) {
            throw new Error(`Could not find ${jdlFile}, make sure the path is correct.`);
        }
        url = new URL(jdlFile, `https://raw.githubusercontent.com/jhipster/jdl-samples/v${packageJson.version}/`).toString();
        jdlFile = path.basename(jdlFile);
    }
    try {
        return await downloadFile(url, jdlFile);
    }
    catch (error) {
        logger.verboseInfo(error.message);
        const branchName = 'v8';
        url = new URL(jdlFile, `https://raw.githubusercontent.com/jhipster/jdl-samples/${branchName}/`).toString();
        return downloadFile(url, jdlFile);
    }
};
export const downloadJdlFiles = async (jdlFiles, options = {}) => {
    logger.debug('cmd: download');
    logger.debug(`jdlFiles: ${inspect(jdlFiles)}`);
    if (!jdlFiles || jdlFiles.length === 0) {
        throw new Error('\nAt least one jdl file is required.\n');
    }
    return Promise.all(jdlFiles.map(filename => downloadJdlFile(filename, options)));
};
const downloadJdlCommand = (positionalArgs, options) => downloadJdlFiles(positionalArgs[0], options);
export default downloadJdlCommand;
