"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMinimalEnvironment = getMinimalEnvironment;
exports.createSortCommandForStdin = createSortCommandForStdin;
exports.createSortCommandForFile = createSortCommandForFile;
exports.spawnSortProcessFromFile = spawnSortProcessFromFile;
exports.spawnSortProcessFromStdin = spawnSortProcessFromStdin;
exports.spawnSortProcess = spawnSortProcess;
const child_process_1 = require("child_process");
const tmp_1 = __importDefault(require("tmp"));
function getMinimalEnvironment() {
    return {
        ...process.env,
        LC_ALL: 'C',
    };
}
function createSortCommandForStdin() {
    // Create a temporary file to store stdin content, then process it
    // This allows us to read the data twice - once for headers, once for sorting
    const tmpFile = tmp_1.default.fileSync({
        prefix: 'jbrowse-sort-gff',
    }).name;
    const sortCmd = `sort -t"\`printf '\\t'\`" -k1,1 -k4,4n`;
    // Save stdin to temp file, extract headers, sort non-headers, then cleanup
    return `cat > ${tmpFile} && (grep "^#" ${tmpFile}; grep -v "^#" ${tmpFile} | ${sortCmd}) && rm -f ${tmpFile}`;
}
function createSortCommandForFile(file) {
    // When reading from a file, we can read it multiple times directly
    // Need to wrap in parentheses to ensure both grep outputs are combined
    return `(grep "^#" "${file}"; grep -v "^#" "${file}" | sort -t"\`printf '\\t'\`" -k1,1 -k4,4n)`;
}
function spawnSortProcessFromFile(file) {
    const command = createSortCommandForFile(file);
    const env = getMinimalEnvironment();
    return (0, child_process_1.spawn)('sh', ['-c', command], {
        env,
        stdio: 'inherit',
    });
}
function spawnSortProcessFromStdin() {
    const command = createSortCommandForStdin();
    const env = getMinimalEnvironment();
    return (0, child_process_1.spawn)('sh', ['-c', command], {
        env,
        stdio: 'inherit',
    });
}
function spawnSortProcess(options) {
    return options.file
        ? spawnSortProcessFromFile(options.file)
        : spawnSortProcessFromStdin();
}
