/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { ID } from "../types/id.mjs";
import { isObject } from "../types/is.mjs";
import { validateString } from "../types/validate.mjs";

export { trimSpaces };

/**
 * This special trim function allows to trim spaces that have been protected by a special escape character.
 *
 * ```
 * <script type="module">
 * import {trimSpaces} from '@schukai/monster/source/util/trimspaces.mjs';
 * trimSpaces(' hello \\ ')
 * </script>
 * ```
 *
 * Hint: One stroke is escaped by the javascript interpreter, the second stroke escapes the stroke.
 *
 * ```text
 * a\ b  ↦ a b
 * a\\ b ↦ a\ b
 * ```
 *
 * @license AGPLv3
 * @since 1.24.0
 * @copyright Volker Schukai
 * @param {string} value
 * @return {string}
 * @throws {TypeError} value is not a string
 */
function trimSpaces(value) {
	validateString(value);

	const placeholder = new Map();
	const regex = /((?<pattern>\\(?<char>.)){1})/gim;

	// The separator for args must be escaped
	// undefined string which should not occur normally and is also not a regex
	const result = value.matchAll(regex);

	for (const m of result) {
		const g = m?.["groups"];
		if (!isObject(g)) {
			continue;
		}

		const p = g?.["pattern"];
		const c = g?.["char"];

		if (p && c) {
			const r = `__${new ID().toString()}__`;
			placeholder.set(r, c);
			value = value.replace(p, r);
		}
	}

	value = value.trim();
	placeholder.forEach((v, k) => {
		value = value.replace(k, `\\${v}`);
	});

	return value;
}
