// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

/**
 * @OncePerLifecycle decorator - ensures method is called only once per lifecycle
 * Automatically resets on specified lifecycle hooks
 */
export function OncePerLifecycle(resetOn: string[] = ['ionViewWillLeave', 'ngOnDestroy']) {
	return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
		const originalMethod = descriptor.value;
		const executedKey = Symbol(`__once_executed_${propertyKey}`);

		descriptor.value = function (this: any, ...args: any[]) {
			if (this[executedKey]) {
				console.warn(`Method ${propertyKey} has already been called in this lifecycle.`);
				return;
			}

			this[executedKey] = true;

			// Auto-reset on specified lifecycle hooks
			resetOn.forEach((hookName) => {
				const originalHook = this[hookName];
				this[hookName] = function (this: any, ...hookArgs: any[]) {
					this[executedKey] = false;
					if (originalHook) {
						return originalHook.apply(this, hookArgs);
					}
				};
			});

			return originalMethod.apply(this, args);
		};

		return descriptor;
	};
}
