"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileStrategy = void 0;
const detect_browser_1 = require("detect-browser");
const json_stringify_safe_1 = __importDefault(require("json-stringify-safe"));
const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
const isEqual_1 = __importDefault(require("lodash/isEqual"));
const rfs = __importStar(require("rotating-file-stream"));
const config_1 = require("../../config");
class FileStrategy {
    constructor() {
        this.applyConfig = this.applyConfig.bind(this);
        config_1.config.on(config_1.config.CONFIG_FILE_UPDATED, this.applyConfig);
        config_1.config.on(config_1.config.CONFIG_SET, this.applyConfig);
    }
    get configuration() {
        return config_1.config.get('logs').transports.file;
    }
    write(methodName, ...args) {
        if (this.writer) {
            const message = this.buildStreamMessage(methodName, args);
            this.writer.write(message);
        }
    }
    initialize() {
        var _a, _b;
        try {
            const isWriteToFile = this.configuration.enabled && ((_a = (0, detect_browser_1.detect)()) === null || _a === void 0 ? void 0 : _a.type) === 'node';
            (_b = this.writer) === null || _b === void 0 ? void 0 : _b.end();
            this.writer = undefined;
            if (isWriteToFile) {
                const { size, maxFiles, interval, maxSize, history } = this.configuration;
                this.writer = rfs.createStream(this.fileNameGenerator.bind(this), {
                    size,
                    maxFiles,
                    interval,
                    maxSize,
                    history: `${history}-${process.pid}.txt`,
                });
            }
            this.prevConfig = (0, cloneDeep_1.default)(this.configuration);
        }
        catch (error) {
            // tslint:disable-next-line: no-console
            console.error('File stream creation error.', error);
        }
    }
    applyConfig() {
        if ((0, isEqual_1.default)(this.prevConfig, this.configuration)) {
            return;
        }
        this.initialize();
    }
    buildStreamMessage(methodName, messages) {
        let message = messages.reduce((prev, curr) => {
            let currString = curr;
            if (typeof curr === 'function') {
                currString = '[Function]';
            }
            if (curr instanceof Error) {
                currString = curr.stack;
            }
            if (typeof currString !== 'string') {
                currString = (0, json_stringify_safe_1.default)(curr);
            }
            return prev + currString + ' ';
        }, '');
        if (methodName.toLowerCase() === 'trace') {
            message = 'Trace: ' + message;
            message += this.getStackTrace();
        }
        message += '\n';
        return message;
    }
    getStackTrace(object = this) {
        Error.captureStackTrace(object);
        return object.stack.replace('Error:', '');
    }
    fileNameGenerator(time, index) {
        const date = typeof time === 'number' ? new Date(time) : time || new Date(Date.now());
        const month = date.getUTCFullYear() + (date.getUTCMonth() + 1 + '').padStart(2, '0');
        const day = (date.getUTCDate() + '').padStart(2, '0');
        const hour = (date.getUTCHours() + '').padStart(2, '0');
        const minute = (date.getUTCMinutes() + '').padStart(2, '0');
        let fileName = `${month}${day}-${hour}${minute}`;
        if (time) {
            fileName += `-${index}`;
        }
        fileName += `-${process.pid}-${this.configuration.name}`;
        return fileName;
    }
}
exports.FileStrategy = FileStrategy;
//# sourceMappingURL=data:application/json;base64, 