/**
 * 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'),
    Logger              = require('../logger'),
    GCAction = require('../system/gc-action'),
    LlmStatTasks = require('./task/llm-stat-tasks');

function CounterManager(agent) {
    this.agent = agent;
    this.time = Date.now();
    
    this.intervalIndex = undefined;
};
CounterManager.plugin={}
CounterManager.prototype.run = function () {
    let self = this;
    process.nextTick(function () {
        var tasks = [];
        tasks.push(new GCAction());

        // 호출 카운트는 ACTIVE_STATS 꼬리의 "LLM:count=N"으로 전송 (_llmMeterCount).
        tasks.push(new LlmStatTasks.LLMActiveStatTask());
        tasks.push(new LlmStatTasks.LLMApiStatusTask());
        tasks.push(new LlmStatTasks.LLMErrorStatTask());
        tasks.push(new LlmStatTasks.LLMFeatureStatTask());
        tasks.push(new LlmStatTasks.LLMPerfStatTask());
        tasks.push(new LlmStatTasks.LLMTokenUsageTask());

        self.intervalIndex = setInterval(function(){
            self.process(tasks);
        },5000);

        self.process(tasks);
    });
};
CounterManager.prototype.stop = function(){
    if(this.intervalIndex){
        clearInterval(this.intervalIndex);
        this.intervalIndex = undefined;
    }
}

CounterManager.prototype.process = function (tasks) {
    var interval = conf.counter_interval || 5000,
        len = tasks.length, self = this, task;

    var now = parseInt(Date.now() / 1000),
        interval_sec = interval / 1000;

    if (now != parseInt(now / interval_sec) * interval_sec) {
        setTimeout(function () {
            self.process(tasks);
        }, 1000, 'whatap');
        return;
    }

    if (conf.counter_enabled) {
        for (var i = 0; i < len; i++) {
            task = tasks[i];
            try{
                task.process();
            } catch (e) {
                Logger.printError('WHATAP-603', 'Counter Manager process ', e, false);
            }
        }

    }
};

module.exports = CounterManager;