/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2024  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue.cqsr;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.OneToOne;

@MappedSuperclass
public abstract class Aggregate<T, E extends Event<T>> {
	/**
	 * Gets the event that was last applied to this aggregate object.
	 */
	@OneToOne
	private E lastApplied;

	/**
	 * Gets the list of events in that apply to this aggregate.
	 *
	 * @return The list of events that apply to this aggregate.
	 */
	public abstract List<? extends E> events();

	/**
	 * Applies all events that still need to be applied to the target aggregate object.
	 *
	 * @param  target The target object that events are to be applied to.
	 * @return        The resulting fully applied target object.
	 */
	public T apply(T target) {
		// Get the list of events as a list sorted by timestamp
		var sortedEvents = events().stream()
				.sorted(Comparator.comparing((Function<Event<?>, LocalDateTime>) Event::getTimestamp))
				.collect(Collectors.toList());

		// For every event after the last applied event, apply them.
		for (int i = sortedEvents.indexOf(lastApplied) + 1; i < sortedEvents.size(); i++) {
			E event = sortedEvents.get(i);
			event.apply(target);
			lastApplied = event;
		}

		return target;
	}
}
