"use strict";
/*
 * @adonisjs/profiler
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfilerAction = void 0;
/// <reference path="../../adonis-typings/profiler.ts" />
const utils_1 = require("@poppinss/utils");
/**
 * Profiler action is used to time the function. A connection can be
 * connected to a row or can be a global action.
 */
class ProfilerAction {
    constructor(label, processor, parentId, data) {
        this.label = label;
        this.processor = processor;
        this.parentId = parentId;
        this.data = data;
        this.start = process.hrtime();
        this.timestamp = Date.now();
        this.ended = false;
    }
    /**
     * Make packet for the action
     */
    makePacket() {
        return {
            parent_id: this.parentId,
            type: 'action',
            label: this.label,
            timestamp: this.timestamp,
            duration: process.hrtime(this.start),
            data: this.data || {},
        };
    }
    /**
     * End profiling action.
     */
    end(data) {
        /**
         * Raise error when end is called twice. Their are high probabilities of
         * end getting called twice
         */
        if (this.ended) {
            throw new utils_1.Exception('attempt to end profiler action twice');
        }
        /**
         * Set the flag
         */
        this.ended = true;
        /**
         * Merge inline data if defined
         */
        if (data) {
            this.data = Object.assign({}, this.data, data);
        }
        this.processor(this.makePacket());
    }
}
exports.ProfilerAction = ProfilerAction;
