'use strict';

// MODULES //

var TransformStream = require( '@stdlib/streams/utils/transform' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isFunction = require( '@stdlib/utils/is-function' );
var canEmitExit = require( './utils/can_emit_exit.js' );
var createHarness = require( './harness' );
var createExitHarness = require( './exit_harness.js' );


// VARIABLES //

var listeners = [];
var harness;


// FUNCTIONS //

/**
* Returns a benchmark harness. If a harness has already been created, returns the cached harness.
*
* @private
* @param {Options} [options] - harness options
* @returns {Function} benchmark harness
*/
function getHarness( options ) {
	var opts;
	if ( harness ) {
		return harness;
	}
	if ( arguments.length ) {
		opts = options;
	} else {
		opts = {};
	}
	opts.autoclose = !canEmitExit;
	harness = createExitHarness( opts, done );
	return harness;
} // end FUNCTION getHarness()

/**
* Callback invoked when a harness finishes running all benchmarks.
*
* @private
*/
function done() {
	var f;
	var i;

	// Inform all the listeners that the harness has finished...
	for ( i = 0; i < listeners.length; i++ ) {
		f = listeners.shift();
		f();
	}
} // end FUNCTION done()

/**
* Creates a results stream.
*
* @memberof bench
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
function createStream( options ) {
	var stream;
	var opts;
	if ( arguments.length ) {
		opts = options;
	} else {
		opts = {};
	}
	// If we have already created a harness, calling this function simply creates another results stream...
	if ( harness ) {
		return harness.createStream( opts );
	}
	stream = new TransformStream( opts );
	opts.stream = stream;

	// Create a harness which uses the created output stream:
	getHarness( opts );

	return stream;
} // end FUNCTION createStream()

/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @memberof bench
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @returns {void}
*/
function onFinish( clbk ) {
	var i;
	if ( !isFunction( clbk ) ) {
		throw new TypeError( 'invalid input argument. Must provide a function. Value: `'+clbk+'`.' );
	}
	// Allow adding a listener only once...
	for ( i = 0; i < listeners.length; i++ ) {
		if ( clbk === listeners[ i ] ) {
			return;
		}
	}
	listeners.push( clbk );
} // end FUNCTION onFinish()


// MAIN //

/**
* Runs a benchmark.
*
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @returns {Benchmark} benchmark harness
*
* @example
* bench( 'beep', function benchmark( b ) {
*     var x;
*     var i;
*     b.comment( 'Running benchmarks...' );
*     b.tic();
*     for ( i = 0; i < b.iterations; i++ ) {
*         x = Math.sin( Math.random() );
*         if ( x !== x ) {
*             b.ok( false, 'should not return NaN' );
*         }
*     }
*     b.toc();
*     if ( x !== x ) {
*         b.ok( false, 'should not return NaN' );
*     }
*     b.comment( 'Finished running benchmarks.' );
*     b.end();
* });
*/
function bench( name, options, benchmark ) {
	var harness = getHarness();
	if ( arguments.length < 2 ) {
		return harness( name );
	}
	if ( arguments.length === 2 ) {
		return harness( name, options );
	}
	return harness( name, options, benchmark );
} // end FUNCTION bench()


// EXPORTS //

module.exports = bench;

setReadOnly( bench, 'createHarness', createHarness );
setReadOnly( bench, 'createStream', createStream );
setReadOnly( bench, 'onFinish', onFinish );

@@ -2075,32 +2075,84 @@
 vide a function%0A
+* @throws %7BError%7D must provide a listener only once%0A
 * @returns %7Bvoid
@@ -2444,22 +2444,97 @@
  ) %7B%0A%09%09%09
-return
+throw new Error( 'invalid input argument. Attempted to add duplicate listener.' )
 ;%0A%09%09%7D%0A%09%7D

Throw if provided a duplicate listener