/**
 * 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 ValueEnum       = require('./valueenum'),
    SummaryValue    = require('./summary-value');

function DoubleSummary() {
    SummaryValue.call(this);
    this.sum = 0;
    this.count = 0;
    this.min = 0;
    this.max =  0;
    this.toString = function() {
        return '[sum=' + this.sum +',count=' + this.count + ',min=' + this.min
            + ',max=' + this.max + "]";
    };
}

DoubleSummary.prototype = new SummaryValue();
DoubleSummary.prototype.constructor = DoubleSummary;
DoubleSummary.prototype.getValueType = function() {
    return ValueEnum.DOUBLE_SUMMARY;
};
DoubleSummary.prototype.write = function(dout) {
    dout.writeDoubleBE(this.sum);
    dout.writeInt32BE(this.count);
    dout.writeDoubleBE(this.min)
    dout.writeDoubleBE(this.max);
};
DoubleSummary.prototype.read = function(din) {
    this.sum = din.readDoubleBE();
    this.count = din.readInt32BE();
    this.min = din.readDoubleBE();
    this.max = din.readDoubleBE();
    return this;
};
DoubleSummary.prototype.toObject = function() {
    return this;
};
DoubleSummary.prototype.add = function(value) {
    if(value == null) {
        return this;
    }

    if(value instanceof SummaryValue) {
        return this.addObject(value);
    }

    if(this.count === 0) {
        this.sum = value;
        this.count = 1;
        this.max = value;
        this.min = value;
    } else {
        this.sum += value;
        this.count++;
        this.max = Math.max(this.max, value);
        this.min = Math.min(this.min, value);
    }
    return this;
};
DoubleSummary.prototype.addCount = function(){
    this.count++;
};
DoubleSummary.prototype.addObject = function (other) {
    if(other.getCount() === 0) {
        return this;
    }
    this.count += other.getCount();
    this.sum += other.doubleSum();
    this.min = Math.min(this.min, other.doubleMin());
    this.max = Math.max(this.max, other.doubleMax());
};
DoubleSummary.prototype.longSum = function() {
    return Long.fromNumber(this.sum);
};
DoubleSummary.prototype.longMin = function() {
    return Long.fromNumber(this.min);
};
DoubleSummary.prototype.longMax = function() {
    return Long.fromNumber(this.max);
};
DoubleSummary.prototype.longAvg = function() {
    return Long.fromNumber(this.count === 0 ? 0 : this.sum / this.count);
};
DoubleSummary.prototype.doubleSum = function() {
    return this.sum;
};
DoubleSummary.prototype.doubleMin = function() {
    return this.min;
};
DoubleSummary.prototype.doubleMax = function() {
    return this.max;
};
DoubleSummary.prototype.doubleAvg = function() {
    return this.count === 0 ? 0 : this.sum/this.count;
};
DoubleSummary.prototype.getCount = function() {
    return this.count;
};

module.exports = DoubleSummary;