var http = require('http');
var _ = require('underscore');
var pcm = require('pcm-boilerplate');
var qmean = require('compute-qmean');
var mean = require('compute-incrmmean');

function NoiseDetection(options, callback) {
    var streamDecoder = new pcm.StreamDecoder(options.format)
    var rmsAvg = mean(2000)
    if (options.triggerLevel && options.triggerLevelMax) {
        function processDb(dB) {
            if (dB > options.triggerLevel && dB < options.triggerLevelMax) {
                callback(dB)
            }
        }
    }else if (options.triggerLevel) {
        function processDb(dB) {
            if (dB > options.triggerLevel) {
                callback(dB)
            }
        }
    } else {
        var processDb = callback
    }
    function processBlock() {
        var block = streamDecoder.read();
        var samples = [];
        var rms;
        var db;
        if (block) {
            _.forEach(block[0], function (sample) {
                samples.push(sample)
            });
            rms = qmean(samples)
            rmsAvg(rms)
            dB = (rms * 100).toFixed(2)
            processDb(dB)
        }
    }
    this.streamDecoder = streamDecoder
    this.write = function(audioData) {
        streamDecoder.write(audioData)
    }
    this.start = function() {
        if(options.url){
            this.httpStream = http.get(options.url, function (source) {
                source.pipe(streamDecoder)
            })
        }
        streamDecoder.on('readable', processBlock)
    }
    this.stop = function() {
        if(this.httpStream && this.httpStream.abort){
          console.log('Close Audio Stream')
          this.httpStream.abort()
        }
    }
}

module.exports = NoiseDetection;
