/**
 * Copyright 2016 the WHATAP project authors. All rights reserved.
 * Use of this source code is governed by a license that
 * can be found in the LICENSE file.
 */

var conf = require('../../conf/configure'),
    TraceContextManager = require('../../trace/trace-context-manager'),
    Logger          = require('../../logger');

function ActiveTransaction() {}
ActiveTransaction.prototype.getActiveStats = function () {
    var stats = new Array(5).fill(0);
    var en = TraceContextManager.getContextEnumeration();

    if(conf.getProperty('debug_activestats_size_enabled', false)){
        Logger.print("WHATAP-DEBUG-ACTIVESTATS-1", "Size: " + TraceContextManager.size(), false);
        Logger.print("WHATAP-DEBUG-ACTIVESTATS-2", "Pid: " + process.pid, false);
    }

    try {
        while (en.hasMoreElements()) {
            var ctx = en.nextElement();
            if (!ctx) {
                break;
            }
            if (ctx.active_sqlhash) {
                stats[1]++;
            } else if (ctx.active_httpc_hash) {
                stats[2]++; // httpc
            } else if (ctx.db_opening) {
                stats[3]++; // dbc
            } else if (ctx.socket_connecting) {
                stats[4]++; // socket
            } else {
                stats[0]++; // method
            }
        }
        return stats;
    } catch (e) {
        Logger.printError("WHATAP-602", 'Active Transaction(process)', e)
        return stats;
    }
};

module.exports = new ActiveTransaction();