/**
 * 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.
 */


function ProfileCollector(context) {
    this.context = context;
    this.buffer = [];
    this.buffer_length = 100 - 10;
    this.position = 0;
    this.parent_index = -1;
}

ProfileCollector.prototype.hasStep = function () {
    return this.position > 0;
};
ProfileCollector.prototype.push = function (step) {
    if(this.position >= this.buffer_length) {
        return;
    }
    step.index = this.position;
    step.parent = this.parent_index;
    this.parent_index = this.position;
    this.buffer[this.position] = step;
    this.position++;
};
ProfileCollector.prototype.add = function (step) {
    if(this.position >= this.buffer_length) {
        return;
    }
    step.index = this.position;
    step.parent = this.parent_index;
    this.buffer[this.position] = step;
    this.position++;
};
ProfileCollector.prototype.addEnd = function (step) {
    if(this.position >= this.buffer.length) {
        return;
    }
    step.index = this.position;
    step.parent = this.parent_index;
    this.buffer[this.position] = step;
    this.position++;
};
ProfileCollector.prototype.pop = function (step) {
    this.parent_index = step.parent;
};
ProfileCollector.prototype.getLastSteps = function (n) {
    var cnt = this.position > n ? n : this.position;
    var buff = new Array(cnt);
    for(var x = this.position - cnt, i=0; i<cnt; i++) {
        buff[i] = this.buffer[x+i];
    }
    return buff;
};
ProfileCollector.prototype.getSteps = function () {
    if(this.position >= this.buffer.length) {
        return this.buffer;
    }
    if(this.position > 0) {
        //clone
        return this.buffer.slice();
    }
};
ProfileCollector.prototype.getStep4Error = function () {
    return this.getLastSteps(5);
};

module.exports = ProfileCollector;