"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexGff3 = void 0;
const tslib_1 = require("tslib");
const util_1 = require("../util");
const cli_progress_1 = require("cli-progress");
const zlib_1 = require("zlib");
const readline_1 = tslib_1.__importDefault(require("readline"));
function indexGff3(config, attributes, inLocation, outLocation, typesToExclude, quiet) {
    return tslib_1.__asyncGenerator(this, arguments, function* indexGff3_1() {
        var e_1, _a;
        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 tslib_1.__await((0, util_1.getLocalOrRemoteStream)(inLocation, outLocation));
        if (!quiet) {
            progressBar.start(totalBytes, 0);
        }
        stream.on('data', chunk => {
            receivedBytes += chunk.length;
            progressBar.update(receivedBytes);
        });
        const rl = readline_1.default.createInterface({
            input: inLocation.match(/.b?gz$/) ? stream.pipe((0, zlib_1.createGunzip)()) : stream,
        });
        try {
            for (var rl_1 = tslib_1.__asyncValues(rl), rl_1_1; rl_1_1 = yield tslib_1.__await(rl_1.next()), !rl_1_1.done;) {
                const line = rl_1_1.value;
                if (line.startsWith('#')) {
                    continue;
                }
                else if (line.startsWith('>')) {
                    break;
                }
                const [seq_id, , type, start, end, , , , col9] = line.split('\t');
                const locStr = `${seq_id}:${start}..${end}`;
                if (!typesToExclude.includes(type)) {
                    // turns gff3 attrs into a map, and converts the arrays into space
                    // separated strings
                    const col9attrs = Object.fromEntries(col9
                        .split(';')
                        .map(f => f.trim())
                        .filter(f => !!f)
                        .map(f => f.split('='))
                        .map(([key, val]) => [
                        key.trim(),
                        decodeURIComponent(val).trim().split(',').join(' '),
                    ]));
                    const attrs = attributes
                        .map(attr => col9attrs[attr])
                        .filter((f) => !!f);
                    if (attrs.length) {
                        const record = JSON.stringify([
                            encodeURIComponent(locStr),
                            encodeURIComponent(trackId),
                            ...attrs.map(a => encodeURIComponent(a)),
                        ]).replace(/,/g, '|');
                        yield yield 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 tslib_1.__await(_a.call(rl_1));
            }
            finally { if (e_1) throw e_1.error; }
        }
        progressBar.stop();
    });
}
exports.indexGff3 = indexGff3;
