import { SEARCH_KEY } from '../../utils';
import { sprintf } from '@gravityforms/utils';

/**
 * @function getActiveFilterLabel
 * @description Get active filter label.
 *
 * @since 5.1.0
 *
 * @param {string}       key       The key of the filter.
 * @param {Array|string} value     The value of the filter.
 * @param {string}       pillLabel The pill label.
 *
 * @return {string} The active filter label.
 */
export const getActiveFilterLabel = ( key = '', value = '', pillLabel = '' ) => {
	if ( key === SEARCH_KEY ) {
		return sprintf( pillLabel, value );
	}
	return '';
};

/**
 * @function getUpdatedFilters
 * @description Get the updated filters.
 * This function updates or adds a filter based on the key and value.
 * Generally used for date and search filters.
 *
 * @since 5.1.0
 *
 * @param {Array}        filters   The array of filters.
 * @param {string}       key       The key of the filter.
 * @param {Array|string} value     The value of the filter.
 * @param {string}       pillLabel The pill label.
 *
 * @return {Array} The updated filters.
 */
export const getUpdatedFilters = (
	filters = [],
	key = '',
	value = '',
	pillLabel = '',
) => {
	const hasFilter = filters.find( ( filter ) => filter.key === key );
	const hasValue = value.length > 0;
	let updatedFilters;
	if ( hasValue && hasFilter ) {
		updatedFilters = filters.map( ( filter ) => {
			if ( filter.key === key ) {
				return {
					...filter,
					value,
					label: getActiveFilterLabel( key, value, pillLabel ),
				};
			}
			return filter;
		} );
	} else if ( hasValue ) {
		updatedFilters = [
			...filters,
			{
				id: key,
				key,
				label: getActiveFilterLabel( key, value, pillLabel ),
				value,
			},
		];
	} else {
		updatedFilters = filters.filter( ( filter ) => filter.key !== key );
	}

	return updatedFilters;
};
