/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var Readable = require( 'readable-stream' ).Readable;
var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isProbability = require( '@stdlib/assert/is-probability' ).isPrimitive;
var isError = require( '@stdlib/assert/is-error' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var rnbinom = require( '@stdlib/random/base/negative-binomial' ).factory;
var string2buffer = require( '@stdlib/buffer/from-string' );
var nextTick = require( '@stdlib/utils/next-tick' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );


// FUNCTIONS //

/**
* Returns the PRNG seed.
*
* @private
* @returns {(PRNGSeedMT19937|null)} seed
*/
function getSeed() {
	return this._prng.seed; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG seed length.
*
* @private
* @returns {(PositiveInteger|null)} seed length
*/
function getSeedLength() {
	return this._prng.seedLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state length.
*
* @private
* @returns {(PositiveInteger|null)} state length
*/
function getStateLength() {
	return this._prng.stateLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {(PositiveInteger|null)} state size (in bytes)
*/
function getStateSize() {
	return this._prng.byteLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the current PRNG state.
*
* @private
* @returns {(PRNGStateMT19937|null)} current state
*/
function getState() {
	return this._prng.state; // eslint-disable-line no-invalid-this
}

/**
* Sets the PRNG state.
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
	this._prng.state = s; // eslint-disable-line no-invalid-this
}

/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
	/* eslint-disable no-invalid-this */
	var FLG;
	var r;

	if ( this._destroyed ) {
		return;
	}
	FLG = true;
	while ( FLG ) {
		this._i += 1;
		if ( this._i > this._iter ) {
			debug( 'Finished generating pseudorandom numbers.' );
			return this.push( null );
		}
		r = this._prng();

		debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i );

		if ( this._objectMode === false ) {
			r = r.toString();
			if ( this._i === 1 ) {
				r = string2buffer( r );
			} else {
				r = string2buffer( this._sep+r );
			}
		}
		FLG = this.push( r );
		if ( this._i%this._siter === 0 ) {
			this.emit( 'state', this.state );
		}
	}

	/* eslint-enable no-invalid-this */
}

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
function destroy( error ) {
	/* eslint-disable no-invalid-this */
	var self;
	if ( this._destroyed ) {
		debug( 'Attempted to destroy an already destroyed stream.' );
		return this;
	}
	self = this;
	this._destroyed = true;

	nextTick( close );

	return this;

	/**
	* Closes a stream.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
			self.emit( 'error', error );
		}
		debug( 'Closing the stream...' );
		self.emit( 'close' );
	}

	/* eslint-enable no-invalid-this */
}


// MAIN //

/**
* Stream constructor for generating a stream of pseudorandom numbers drawn from a binomial distribution.
*
* @constructor
* @param {PositiveNumber} r - number of successes until experiment is stopped
* @param {Probability} p - success probability
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @throws {TypeError} `r` must be a positive number
* @throws {TypeError} `p` must be a probability
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( chunk ) {
*    console.log( chunk.toString() );
* }
*
* var opts = {
*     'iter': 10
* };
*
* var stream = new RandomStream( 20.0, 0.2, opts );
*
* stream.pipe( inspectStream( log )  );
*/
function RandomStream( r, p, options ) {
	var opts;
	var err;
	if ( !( this instanceof RandomStream ) ) {
		if ( arguments.length > 2 ) {
			return new RandomStream( r, p, options );
		}
		return new RandomStream( r, p );
	}
	if ( !isPositiveNumber( r ) ) {
		throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `'+r+'`.' );
	}
	if ( !isProbability( p ) ) {
		throw new TypeError( 'invalid argument. Second argument must be a probability. Value: `'+p+'`.' );
	}
	opts = copy( DEFAULTS );
	if ( arguments.length > 2 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Make the stream a readable stream:
	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
	Readable.call( this, opts );

	// Destruction state:
	setNonEnumerable( this, '_destroyed', false );

	// Cache whether the stream is operating in object mode:
	setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );

	// Cache the separator:
	setNonEnumerableReadOnly( this, '_sep', opts.sep );

	// Cache the total number of iterations:
	setNonEnumerableReadOnly( this, '_iter', opts.iter );

	// Cache the number of iterations after which to emit the underlying PRNG state:
	setNonEnumerableReadOnly( this, '_siter', opts.siter );

	// Initialize an iteration counter:
	setNonEnumerable( this, '_i', 0 );

	// Create the underlying PRNG:
	setNonEnumerableReadOnly( this, '_prng', rnbinom( r, p, opts ) );
	setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG );

	return this;
}

/*
* Inherit from the `Readable` prototype.
*/
inherit( RandomStream, Readable );

/**
* PRNG seed.
*
* @name seed
* @memberof RandomStream.prototype
* @type {(PRNGSeedMT19937|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );

/**
* PRNG seed length.
*
* @name seedLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );

/**
* PRNG state getter/setter.
*
* @name state
* @memberof RandomStream.prototype
* @type {(PRNGStateMT19937|null)}
* @throws {Error} must provide a valid state
*/
setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );

/**
* PRNG state length.
*
* @name stateLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );

/**
* PRNG state size (in bytes).
*
* @name byteLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );

/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof RandomStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
setNonEnumerableReadOnly( RandomStream.prototype, '_read', read );

/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof RandomStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy );


// EXPORTS //

module.exports = RandomStream;
