"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const analytics_broker_1 = require("./analytics-broker");
const file_log_service_1 = require("../../detached-processes/file-log-service");
const yok_1 = require("../../common/yok");
const pathToBootstrap = process.argv[2];
if (!pathToBootstrap || !fs.existsSync(pathToBootstrap)) {
    throw new Error("Invalid path to bootstrap.");
}
const logFile = process.argv[3];
require(pathToBootstrap);
const analyticsLoggingService = yok_1.injector.resolve(file_log_service_1.FileLogService, { logFile });
analyticsLoggingService.logData({ message: "Initializing AnalyticsBroker." });
const analyticsBroker = yok_1.injector.resolve(analytics_broker_1.AnalyticsBroker, {
    pathToBootstrap,
    analyticsLoggingService,
});
let trackingQueue = Promise.resolve();
const sendDataForTracking = async (data) => {
    trackingQueue = trackingQueue.then(() => analyticsBroker.sendDataForTracking(data));
    await trackingQueue;
};
const finishTracking = async (data) => {
    analyticsLoggingService.logData({
        message: `analytics-broker-process finish tracking started`,
    });
    await trackingQueue;
    analyticsLoggingService.logData({
        message: `analytics-broker-process tracking finished`,
    });
};
const killCurrentProcessGracefully = () => {
    yok_1.injector.dispose();
    process.exit();
};
process.on("message", async (data) => {
    analyticsLoggingService.logData({
        message: `analytics-broker-process received message of type: ${JSON.stringify(data)}`,
    });
    if (data.type === "FinishTracking") {
        await finishTracking();
        if (process.connected) {
            analyticsLoggingService.logData({
                message: `analytics-broker-process will send ${"ProcessFinishedTasks"} message`,
            });
            process.send("ProcessFinishedTasks", () => {
                analyticsLoggingService.logData({
                    message: `analytics-broker-process sent ${"ProcessFinishedTasks"} message and will exit gracefully now`,
                });
                killCurrentProcessGracefully();
            });
        }
        return;
    }
    await sendDataForTracking(data);
});
process.on("disconnect", async () => {
    analyticsLoggingService.logData({
        message: "analytics-broker-process received process.disconnect event",
    });
    await finishTracking();
    killCurrentProcessGracefully();
});
analyticsLoggingService.logData({
    message: `analytics-broker-process will send ${"ProcessReadyToReceive"} message`,
});
process.send("ProcessReadyToReceive");
