"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimelineProfilerService = void 0;
const decorators_1 = require("../common/decorators");
const yok_1 = require("../common/yok");
const path = require("path");
const nativescript_cli_1 = require("../nativescript-cli");
const color_1 = require("../color");
const TIMELINE_LOG_RE = /Timeline:\s*(\d*.?\d*ms:\s*)?([^\:]*\:)?(.*)\((\d*.?\d*)ms\.?\s*-\s*(\d*.\d*)ms\.?\)/;
var ChromeTraceEventPhase;
(function (ChromeTraceEventPhase) {
    ChromeTraceEventPhase["BEGIN"] = "B";
    ChromeTraceEventPhase["END"] = "E";
    ChromeTraceEventPhase["INSTANT"] = "i";
    ChromeTraceEventPhase["COMPLETE"] = "X";
})(ChromeTraceEventPhase || (ChromeTraceEventPhase = {}));
class TimelineProfilerService {
    constructor($projectConfigService, $fs, $logger) {
        this.$projectConfigService = $projectConfigService;
        this.$fs = $fs;
        this.$logger = $logger;
        this.timelines = new Map();
        this.attachedExitHandler = false;
    }
    attachExitHanlder() {
        if (!this.attachedExitHandler) {
            this.$logger.info('attached "SIGINT" handler to write timeline data.');
            (0, nativescript_cli_1.originalProcessOn)("SIGINT", this.writeTimelines.bind(this));
            this.attachedExitHandler = true;
        }
    }
    processLogData(data, deviceIdentifier) {
        if (!this.isEnabled()) {
            return;
        }
        this.attachExitHanlder();
        if (!this.timelines.has(deviceIdentifier)) {
            this.timelines.set(deviceIdentifier, {
                startPoint: null,
                timeline: [],
            });
        }
        const deviceTimeline = this.timelines.get(deviceIdentifier);
        data.split("\n").forEach((line) => {
            var _a;
            const trace = this.toTrace(line.trim());
            if (trace) {
                (_a = deviceTimeline.startPoint) !== null && _a !== void 0 ? _a : (deviceTimeline.startPoint = trace.from);
                deviceTimeline.timeline.push(trace);
            }
        });
    }
    isEnabled() {
        return this.$projectConfigService.getValue("profiling") === "timeline";
    }
    toTrace(text) {
        var _a, _b;
        const result = text.match(TIMELINE_LOG_RE);
        if (!result) {
            return;
        }
        const trace = {
            domain: (_a = result[2]) === null || _a === void 0 ? void 0 : _a.trim().replace(":", ""),
            name: result[3].trim(),
            from: parseFloat(result[4]),
            to: parseFloat(result[5]),
        };
        return {
            pid: 1,
            tid: 1,
            ts: trace.from * 1000,
            dur: (trace.to - trace.from) * 1000,
            name: trace.name,
            cat: (_b = trace.domain) !== null && _b !== void 0 ? _b : "default",
            ph: ChromeTraceEventPhase.COMPLETE,
        };
    }
    writeTimelines() {
        this.$logger.info("\n\nWriting timeline data to json...");
        this.timelines.forEach((deviceTimeline, deviceIdentifier) => {
            const deviceTimelineFileName = `timeline-${deviceIdentifier}.json`;
            this.$fs.writeJson(path.resolve(process.cwd(), deviceTimelineFileName), deviceTimeline.timeline);
            this.$logger.info(`Timeline data for device ${color_1.color.cyan(deviceIdentifier)} written to ${color_1.color.green(deviceTimelineFileName)}`);
        });
        this.$logger.info(color_1.color.green("\n\nTo view the timeline data, open the following URL in Chrome, and load the json file:"));
        this.$logger.info(color_1.color.green("devtools://devtools/bundled/inspector.html?panel=timeline\n\n"));
        process.exit();
    }
}
__decorate([
    (0, decorators_1.cache)()
], TimelineProfilerService.prototype, "isEnabled", null);
exports.TimelineProfilerService = TimelineProfilerService;
yok_1.injector.register("timelineProfilerService", TimelineProfilerService);
