"use strict";
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const ExifTool_1 = require("./ExifTool");
describe("ExifTool disposal", () => {
    it("should support Symbol.dispose", () => {
        const et = new ExifTool_1.ExifTool();
        (0, chai_1.expect)(et[Symbol.dispose]).to.be.a("function");
    });
    it("should support Symbol.asyncDispose", () => {
        const et = new ExifTool_1.ExifTool();
        (0, chai_1.expect)(et[Symbol.asyncDispose]).to.be.a("function");
    });
    it("should dispose synchronously without throwing", () => {
        const et = new ExifTool_1.ExifTool();
        (0, chai_1.expect)(() => et[Symbol.dispose]()).to.not.throw();
        // The sync disposal calls end() immediately, so it should be marked as ended
        // even though the actual cleanup happens asynchronously
        (0, chai_1.expect)(et.ended).to.be.true;
    });
    it("should dispose asynchronously", async () => {
        const et = new ExifTool_1.ExifTool();
        await et[Symbol.asyncDispose]();
        (0, chai_1.expect)(et.ended).to.be.true;
    });
    it("should be idempotent", async () => {
        const et = new ExifTool_1.ExifTool();
        await et[Symbol.asyncDispose]();
        (0, chai_1.expect)(et.ended).to.be.true;
        // Should not throw on second call
        await et[Symbol.asyncDispose]();
        (0, chai_1.expect)(et.ended).to.be.true;
    });
    it("should handle timeout in async disposal gracefully", async () => {
        const et = new ExifTool_1.ExifTool();
        // Mock a slow .end() method by stubbing it
        const originalEnd = et.end.bind(et);
        let endCalled = false;
        let forcefulEndCalled = false;
        et.end = async (graceful) => {
            if (graceful) {
                endCalled = true;
                // Simulate a hanging cleanup that takes longer than the timeout
                await new Promise((resolve) => setTimeout(resolve, 6000));
                return originalEnd(false);
            }
            else {
                forcefulEndCalled = true;
                // Forceful cleanup should work quickly
                return originalEnd(false);
            }
        };
        // The async dispose should timeout and attempt forceful cleanup
        await et[Symbol.asyncDispose]();
        (0, chai_1.expect)(endCalled).to.be.true;
        (0, chai_1.expect)(forcefulEndCalled).to.be.true;
        (0, chai_1.expect)(et.ended).to.be.true;
    }).timeout(8000);
    it("should actually stop child processes on disposal", async () => {
        const et = new ExifTool_1.ExifTool({ maxProcs: 2 });
        // Force creation of child processes by doing some work
        await et.version();
        await et.version(); // Second call to potentially spawn another process
        // Verify we have running processes
        const pidsBeforeDisposal = et.pids;
        (0, chai_1.expect)(pidsBeforeDisposal.length).to.be.greaterThan(0);
        // Dispose and verify processes are cleaned up
        await et[Symbol.asyncDispose]();
        const pidsAfterDisposal = et.pids;
        (0, chai_1.expect)(pidsAfterDisposal).to.eql([]);
        (0, chai_1.expect)(et.ended).to.be.true;
    });
    it("should mark as ended immediately in sync disposal", () => {
        const et = new ExifTool_1.ExifTool();
        (0, chai_1.expect)(et.ended).to.be.false;
        et[Symbol.dispose]();
        // Should be marked as ended immediately, even though cleanup is async
        (0, chai_1.expect)(et.ended).to.be.true;
    });
    // This test demonstrates the usage with TypeScript 5.2+
    it("should work with using keyword", async () => {
        let _; // < to hold reference outside using block
        {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
                const et = __addDisposableResource(env_1, new ExifTool_1.ExifTool(), false);
                _ = et;
                (0, chai_1.expect)(et.ended).to.be.false;
            }
            catch (e_1) {
                env_1.error = e_1;
                env_1.hasError = true;
            }
            finally {
                __disposeResources(env_1);
            }
        }
        (0, chai_1.expect)(_.ended).to.be.true;
    });
    it("should work with await using keyword", async () => {
        let _; // < to hold reference outside using block
        {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
                const et = __addDisposableResource(env_2, new ExifTool_1.ExifTool(), true);
                _ = et;
                (0, chai_1.expect)(et.ended).to.be.false;
                const version = await et.version();
                (0, chai_1.expect)(version).to.match(/^\d+\.\d+/);
            }
            catch (e_2) {
                env_2.error = e_2;
                env_2.hasError = true;
            }
            finally {
                const result_1 = __disposeResources(env_2);
                if (result_1)
                    await result_1;
            }
        }
        (0, chai_1.expect)(_.ended).to.be.true;
    });
});
//# sourceMappingURL=ExifTool.dispose.spec.js.map