"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeFileHandler = void 0;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
function makeFileHandler(_a) {
    var _b;
    var { filename = (_b = process.env.APPLITOOLS_LOG_FILE) !== null && _b !== void 0 ? _b : 'eyes.log', append = true, } = _a === void 0 ? {} : _a;
    let writer = null;
    return { log, open, close };
    function open() {
        const filepath = path.normalize(filename);
        ensureDirectoryExistence(filepath);
        writer = fs.createWriteStream(filepath, { flags: append ? 'a' : 'w', encoding: 'utf8' });
    }
    function close() {
        if (!writer)
            return;
        writer.end();
        writer = null;
    }
    function log(message) {
        if (!writer)
            open();
        writer.write(message + os.EOL);
    }
}
exports.makeFileHandler = makeFileHandler;
function ensureDirectoryExistence(filename) {
    const dirname = path.dirname(filename);
    if (!fs.existsSync(dirname)) {
        ensureDirectoryExistence(dirname);
        fs.mkdirSync(dirname);
    }
}
