"use strict";
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexVcf = void 0;
const cli_progress_1 = require("cli-progress");
const zlib_1 = require("zlib");
const readline_1 = __importDefault(require("readline"));
const util_1 = require("../util");
function indexVcf({ config, attributesToIndex, inLocation, outLocation, quiet, }) {
    return __asyncGenerator(this, arguments, function* indexVcf_1() {
        var _a, e_1, _b, _c;
        const { trackId } = config;
        // 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 receivedBytes = 0;
        const { totalBytes, stream } = yield __await((0, util_1.getLocalOrRemoteStream)(inLocation, outLocation));
        if (!quiet) {
            progressBar.start(totalBytes, 0);
        }
        stream.on('data', chunk => {
            receivedBytes += chunk.length;
            progressBar.update(receivedBytes);
        });
        const gzStream = inLocation.match(/.b?gz$/)
            ? stream.pipe((0, zlib_1.createGunzip)())
            : stream;
        const rl = readline_1.default.createInterface({
            input: gzStream,
        });
        try {
            for (var _d = true, rl_1 = __asyncValues(rl), rl_1_1; rl_1_1 = yield __await(rl_1.next()), _a = rl_1_1.done, !_a; _d = true) {
                _c = rl_1_1.value;
                _d = false;
                const line = _c;
                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 || +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 || '')),
                    ]).replaceAll(',', '|');
                    yield yield __await(`${record} ${[...new Set(attrs)].join(' ')}\n`);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_d && !_a && (_b = rl_1.return)) yield __await(_b.call(rl_1));
            }
            finally { if (e_1) throw e_1.error; }
        }
        progressBar.stop();
    });
}
exports.indexVcf = indexVcf;
