"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateMeta = exports.supported = exports.guessAdapterFromFileName = exports.isURL = exports.createRemoteStream = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const follow_redirects_1 = require("follow-redirects");
const path_1 = tslib_1.__importDefault(require("path"));
// Method for handing off the parsing of a gff3 file URL.
// Calls the proper parser depending on if it is gzipped or not.
// Returns a @gmod/gff stream.
async function createRemoteStream(urlIn) {
    const newUrl = new URL(urlIn);
    const fetcher = newUrl.protocol === 'https:' ? follow_redirects_1.https : follow_redirects_1.http;
    return new Promise((resolve, reject) => fetcher.get(urlIn, resolve).on('error', reject));
}
exports.createRemoteStream = createRemoteStream;
// Checks if the passed in string is a valid URL.
// Returns a boolean.
function isURL(FileName) {
    let url;
    try {
        url = new URL(FileName);
    }
    catch (_) {
        return false;
    }
    return url.protocol === 'http:' || url.protocol === 'https:';
}
exports.isURL = isURL;
function guessAdapterFromFileName(filePath) {
    const uri = isURL(filePath) ? filePath : path_1.default.resolve(filePath);
    const name = path_1.default.basename(uri);
    if (/\.vcf\.b?gz$/i.test(filePath)) {
        return {
            trackId: name,
            name: name,
            assemblyNames: [],
            adapter: {
                type: 'VcfTabixAdapter',
                vcfGzLocation: { uri },
            },
        };
    }
    else if (/\.gff3?\.b?gz$/i.test(filePath)) {
        return {
            trackId: name,
            name,
            assemblyNames: [],
            adapter: {
                type: 'Gff3TabixAdapter',
                gffGzLocation: { uri },
            },
        };
    }
    else if (/\.gtf?$/i.test(filePath)) {
        return {
            trackId: name,
            name,
            assemblyNames: [],
            adapter: {
                type: 'GtfTabixAdapter',
                gtfGzLocation: { uri },
            },
        };
    }
    else {
        throw new Error(`Unsupported file type ${filePath}`);
    }
}
exports.guessAdapterFromFileName = guessAdapterFromFileName;
function supported(type) {
    return ['Gff3TabixAdapter', 'GtfTabixAdapter', 'VcfTabixAdapter'].includes(type);
}
exports.supported = supported;
/**
 * Generates metadata of index given a filename (trackId or assembly)
 * @param name -  assembly name or trackId
 * @param attributes -  attributes indexed
 * @param include -  feature types included from index
 * @param exclude -  feature types excluded from index
 * @param configs - list of track
 */
async function generateMeta({ configs, attributes, outDir, name, exclude, assemblyNames, }) {
    const tracks = configs.map(config => {
        const { trackId, textSearching, adapter } = config;
        const includeExclude = (textSearching === null || textSearching === void 0 ? void 0 : textSearching.indexingFeatureTypesToExclude) || exclude;
        const metaAttrs = (textSearching === null || textSearching === void 0 ? void 0 : textSearching.indexingAttributes) || attributes;
        return {
            trackId: trackId,
            attributesIndexed: metaAttrs,
            excludedTypes: includeExclude,
            adapterConf: adapter,
        };
    });
    fs_1.default.writeFileSync(path_1.default.join(outDir, 'trix', `${name}_meta.json`), JSON.stringify({
        dateCreated: new Date().toISOString(),
        tracks,
        assemblyNames,
    }, null, 2));
}
exports.generateMeta = generateMeta;
