/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

/**
 * Extracts longname from strings like 'Array.<module:ui...>'.
 * @param {String} str
 * @returns {Object|null} result
 * @returns {Object} result.longname
 * @returns {Object} result.prefix
 * @returns {Object} result.suffix
 */
module.exports = str => {
	if ( typeof str !== 'string' ) {
		return {
			longnames: [ '' ]
		};
	}

	str = str.replace( 'function()', 'Function' );

	const result = {
		longnames: [ str ]
	};

	if ( str.indexOf( '.<' ) !== -1 ) {
		const match = /^([\w]+\.<\(*)([^)>]+)([)>]+)$/.exec( str );

		if ( match ) {
			result.prefix = match[ 1 ];
			result.longnames = match[ 2 ].split( /[|,]+/ );
			result.longnames = result.longnames.map( l => l.trim() );
			result.suffix = match[ 3 ];
			result.separators = [];

			const separatorsRegex = /[,|]/g;
			let separatorsMatch = separatorsRegex.exec( match[ 2 ] );

			while ( separatorsMatch !== null ) {
				if ( separatorsMatch[ 0 ] === ',' ) {
					result.separators.push( `${ separatorsMatch[ 0 ] } ` );
				} else {
					result.separators.push( ` ${ separatorsMatch[ 0 ] } ` );
				}

				separatorsMatch = separatorsRegex.exec( match[ 2 ] );
			}
		}
	} else if ( str.indexOf( '[]' ) !== -1 ) {
		result.prefix = '';
		result.longnames = [ str.substring( 0, str.indexOf( '[]' ) ).trim() ];
		result.suffix = '[]';
	}

	return result;
};
