"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeIxx = makeIxx;
const util_1 = require("util");
const stream_1 = require("stream");
const events_1 = require("events");
const fs_1 = __importDefault(require("fs"));
const readline_1 = __importDefault(require("readline"));
// locals
const util_2 = require("./util");
const optimizePrefixSize_1 = require("./optimizePrefixSize");
const ADDRESS_SIZE = 10;
const streamFinished = (0, util_1.promisify)(stream_1.finished); // (A)
async function makeIxx(inIx, outIxx, prefixSizeParam) {
    const out = fs_1.default.createWriteStream(outIxx);
    const prefixSize = prefixSizeParam !== null && prefixSizeParam !== void 0 ? prefixSizeParam : (await (0, optimizePrefixSize_1.optimizePrefixSize)(inIx));
    try {
        const fileStream = fs_1.default.createReadStream(inIx);
        const rl = readline_1.default.createInterface({
            input: fileStream,
        });
        let lastPrefix;
        let writtenPrefix;
        let writtenPos = -util_2.binSize;
        let startPrefixPos = 0;
        let bytes = 0;
        for await (const line of rl) {
            const [word] = line.split(/\s/);
            const curPrefix = (0, util_2.getPrefix)(word, prefixSize);
            if (curPrefix !== lastPrefix) {
                startPrefixPos = bytes;
            }
            if (bytes - writtenPos >= util_2.binSize && curPrefix !== writtenPrefix) {
                const res = out.write(`${curPrefix}${startPrefixPos
                    .toString(16)
                    .toUpperCase()
                    .padStart(ADDRESS_SIZE, '0')}\n`);
                // Handle backpressure
                // ref https://nodesource.com/blog/understanding-streams-in-nodejs/
                if (!res) {
                    await (0, events_1.once)(out, 'drain');
                }
                writtenPos = bytes;
                writtenPrefix = curPrefix;
            }
            lastPrefix = curPrefix;
            bytes += line.length + 1;
        }
    }
    finally {
        out.end();
        await streamFinished(out);
    }
}
//# sourceMappingURL=makeIxx.js.map