"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexVcf = void 0;
const tslib_1 = require("tslib");
const common_1 = require("../types/common");
const cli_progress_1 = require("cli-progress");
const zlib_1 = require("zlib");
const readline_1 = (0, tslib_1.__importDefault)(require("readline"));
const path_1 = (0, tslib_1.__importDefault)(require("path"));
const fs_1 = (0, tslib_1.__importDefault)(require("fs"));
function indexVcf(config, attributesToIndex, outLocation, typesToExclude, quiet) {
    return (0, tslib_1.__asyncGenerator)(this, arguments, function* indexVcf_1() {
        var e_1, _a;
        const { adapter, trackId } = config;
        const { vcfGzLocation: { uri }, } = adapter;
        // progress bar code was aided by blog post at
        // https://webomnizz.com/download-a-file-with-progressbar-using-node-js/
        const progressBar = new cli_progress_1.SingleBar({
            format: '{bar} ' + trackId + ' {percentage}% | ETA: {eta}s',
            etaBuffer: 2000,
        }, cli_progress_1.Presets.shades_classic);
        let fileDataStream;
        let totalBytes = 0;
        let receivedBytes = 0;
        if ((0, common_1.isURL)(uri)) {
            fileDataStream = yield (0, tslib_1.__await)((0, common_1.createRemoteStream)(uri));
            totalBytes = +(fileDataStream.headers['content-length'] || 0);
        }
        else {
            const filename = path_1.default.isAbsolute(uri) ? uri : path_1.default.join(outLocation, uri);
            totalBytes = fs_1.default.statSync(filename).size;
            fileDataStream = fs_1.default.createReadStream(filename);
        }
        if (!quiet) {
            progressBar.start(totalBytes, 0);
        }
        fileDataStream.on('data', chunk => {
            receivedBytes += chunk.length;
            progressBar.update(receivedBytes);
        });
        const gzStream = uri.endsWith('.gz')
            ? fileDataStream.pipe((0, zlib_1.createGunzip)())
            : fileDataStream;
        const rl = readline_1.default.createInterface({
            input: gzStream,
        });
        try {
            for (var rl_1 = (0, tslib_1.__asyncValues)(rl), rl_1_1; rl_1_1 = yield (0, tslib_1.__await)(rl_1.next()), !rl_1_1.done;) {
                const line = rl_1_1.value;
                if (line.startsWith('#')) {
                    continue;
                }
                // eslint-disable-next-line @typescript-eslint/no-unused-vars
                const [ref, pos, id, _ref, _alt, _qual, _filter, info] = line.split('\t');
                // turns gff3 attrs into a map, and converts the arrays into space
                // separated strings
                const fields = Object.fromEntries(info
                    .split(';')
                    .map(f => f.trim())
                    .filter(f => !!f)
                    .map(f => f.split('='))
                    .map(([key, val]) => [
                    key.trim(),
                    val ? decodeURIComponent(val).trim().split(',').join(' ') : undefined,
                ]));
                const end = fields.END;
                const locStr = `${ref}:${pos}..${end ? end : +pos + 1}`;
                if (id === '.') {
                    continue;
                }
                const infoAttrs = attributesToIndex
                    .map(attr => fields[attr])
                    .filter((f) => !!f);
                const ids = id.split(',');
                for (let i = 0; i < ids.length; i++) {
                    const id = ids[i];
                    const attrs = [id];
                    const record = JSON.stringify([
                        encodeURIComponent(locStr),
                        encodeURIComponent(trackId),
                        encodeURIComponent(id || ''),
                        ...infoAttrs.map(a => encodeURIComponent(a || '')),
                    ]).replace(/,/g, '|');
                    yield yield (0, tslib_1.__await)(`${record} ${[...new Set(attrs)].join(' ')}\n`);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (rl_1_1 && !rl_1_1.done && (_a = rl_1.return)) yield (0, tslib_1.__await)(_a.call(rl_1));
            }
            finally { if (e_1) throw e_1.error; }
        }
        progressBar.stop();
    });
}
exports.indexVcf = indexVcf;
