"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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 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 = $injector.resolve(file_log_service_1.FileLogService, { logFile });
analyticsLoggingService.logData({ message: "Initializing AnalyticsBroker." });
const analyticsBroker = $injector.resolve(analytics_broker_1.AnalyticsBroker, { pathToBootstrap, analyticsLoggingService });
let trackingQueue = Promise.resolve();
const sendDataForTracking = (data) => __awaiter(this, void 0, void 0, function* () {
    trackingQueue = trackingQueue.then(() => analyticsBroker.sendDataForTracking(data));
    yield trackingQueue;
});
const finishTracking = (data) => __awaiter(this, void 0, void 0, function* () {
    analyticsLoggingService.logData({ message: `analytics-broker-process finish tracking started` });
    yield trackingQueue;
    analyticsLoggingService.logData({ message: `analytics-broker-process tracking finished` });
    $injector.dispose();
    process.exit();
});
const trackPreviewAppData = (data) => __awaiter(this, void 0, void 0, function* () {
    const mobileHelper = $injector.resolve("mobileHelper");
    const devicesService = $injector.resolve("devicesService");
    yield devicesService.initialize({ platform: data.platform, skipDeviceDetectionInterval: true, skipEmulatorStart: true });
    const devices = yield devicesService.getDevicesForPlatform(data.platform);
    _.each(devices, (device) => __awaiter(this, void 0, void 0, function* () {
        try {
            let previewAppFilePath = null;
            if (mobileHelper.isAndroidPlatform(device.deviceInfo.platform)) {
                previewAppFilePath = "/sdcard/org.nativescript.preview/device.json";
            }
            else if (mobileHelper.isiOSPlatform(device.deviceInfo.platform)) {
                previewAppFilePath = "Documents/device.json";
            }
            const previewAppFileContent = yield device.fileSystem.getFileContent(previewAppFilePath, "org.nativescript.preview");
            const previewAppDeviceId = JSON.parse(previewAppFileContent).id;
            data.label += `_${previewAppDeviceId}`;
            analyticsLoggingService.logData({ message: `analytics-broker-process will send the data from preview app: ${data}` });
            yield sendDataForTracking(data);
        }
        catch (err) {
        }
    }));
});
process.on("message", (data) => __awaiter(this, void 0, void 0, function* () {
    analyticsLoggingService.logData({ message: `analytics-broker-process received message of type: ${JSON.stringify(data)}` });
    if (data.type === "PreviewAppData") {
        yield trackPreviewAppData(data);
        return;
    }
    yield sendDataForTracking(data);
}));
process.on("disconnect", () => __awaiter(this, void 0, void 0, function* () {
    analyticsLoggingService.logData({ message: "analytics-broker-process received process.disconnect event" });
    yield finishTracking();
}));
analyticsLoggingService.logData({ message: `analytics-broker-process will send ${"ProcessReadyToReceive"} message` });
process.send("ProcessReadyToReceive");
