/**
 * 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'),
    KeyGen = require('./keygen');

var TraceHelper = {
    check_seq: 1
};

/**
 * Inter-transaction trace auto-on functionality
 * Used for multi-transaction tracing based on sampling rate
 */
TraceHelper.interTxTraceAutoOn = function(ctx) {
    if (conf.mtrace_enabled == false || ctx.httpc_checked || !ctx.mtid.isZero())
        return;

    ctx.httpc_checked = true;

    if (conf.mtrace_rate >= 100) {
        ctx.mtid = KeyGen.getMtid();
        return;
    }

    TraceHelper.check_seq++;

    switch (Math.floor(conf.mtrace_rate / 10)) {
        case 10:
            ctx.mtid = KeyGen.getMtid();
            break;
        case 9:
            if (TraceHelper.check_seq % 10 !== 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 8:
            if (TraceHelper.check_seq % 5 !== 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 7:
            if (TraceHelper.check_seq % 4 !== 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 6:
            if (TraceHelper.check_seq % 3 !== 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 5:
            if (TraceHelper.check_seq % 2 === 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 4:
            if (TraceHelper.check_seq % 3 === 0 || TraceHelper.check_seq % 5 === 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 3:
            if (TraceHelper.check_seq % 4 === 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 2:
            if (TraceHelper.check_seq % 5 === 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 1:
            if (TraceHelper.check_seq % 10 === 0)
                ctx.mtid = KeyGen.getMtid();
            break;
        case 0:
        default:
            break;
    }
};

/**
 * Reset the sequence counter (useful for testing or long-running processes)
 */
TraceHelper.resetSequence = function() {
    TraceHelper.check_seq = 1;
};

/**
 * Get current sequence counter (for debugging)
 */
TraceHelper.getSequence = function() {
    return TraceHelper.check_seq;
};

module.exports = TraceHelper;