/**
* @license Apache-2.0
*
* Copyright (c) 2022 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 isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var format = require( '@stdlib/string/format' );
var logger = require( './../../log' );


// MAIN //

/**
* Inserts array element values into a format string and prints the result.
*
* @param {string} str - format string
* @param {...(Collection|*)} args - collections or values
* @throws {TypeError} first argument must be a string
* @throws {RangeError} provided collections must have the same length
* @returns {void}
*/
function logEach( str ) {
	var strides;
	var offsets;
	var values;
	var nargs;
	var args;
	var len;
	var v;
	var s;
	var i;
	var j;
	if ( !isString( str ) ) {
		throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) );
	}
	nargs = arguments.length;
	strides = [];
	args = [];
	for ( i = 1; i < nargs; i++ ) {
		v = arguments[ i ];
		if ( isCollection( v ) ) {
			args.push( v );
			strides.push( 1 );
			len = v.length;
			i += 1;
			break;
		} else {
			args.push( [ v ] );
			strides.push( 0 );
		}
	}
	if ( len === void 0 ) {
		len = 1;
	}
	for ( ; i < nargs; i++ ) {
		v = arguments[ i ];
		if ( isCollection( v ) ) {
			if ( v.length !== len ) {
				throw new RangeError( 'invalid argument. Provided collections must have the same length.' );
			}
			s = 1;
		} else {
			v = [ v ];
			s = 0;
		}
		args.push( v );
		strides.push( s );
	}
	values = [ str ];
	offsets = [];
	for ( i = 1; i < nargs; i++ ) {
		values.push( null );
		offsets.push( 0 );
	}
	for ( i = 0; i < len; i++ ) {
		for ( j = 0; j < nargs-1; j++ ) {
			values[ j+1 ] = args[ j ][ offsets[ j ] ];
			offsets[ j ] += strides[ j ];
		}
		logger( format.apply( null, values ) );
	}
}


// EXPORTS //

module.exports = logEach;
