/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2021  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.realtime;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import lombok.NoArgsConstructor;
import nl.tudelft.labracore.lib.security.user.Person;
import nl.tudelft.queue.dto.create.SubscriptionCreateDTO;
import nl.tudelft.queue.properties.PushProperties;

import org.springframework.beans.factory.annotation.Autowired;

@NoArgsConstructor
public class SubscriptionContainer {

	@Autowired
	private PushProperties properties;

	/**
	 * A map mapping person IDs to their set of subscriptions. This set of subscriptions is maintained as a
	 * limited cache using LRU to throw out entries when going over capacity.
	 */
	private final Map<Long, Set<Subscription>> subscriptions = new ConcurrentHashMap<>();

	/**
	 * Gets all subscriptions for a specific person by their authentication person object.
	 *
	 * @param  person The authenticated person object to get subscriptions for.
	 * @return        The set of all subscriptions currently owned by this person.
	 */
	public Set<Subscription> get(Person person) {
		return get(person.getId());
	}

	/**
	 * Gets all subscriptions for a specific person by their person id.
	 *
	 * @param  person The id of the person to get subscriptions for.
	 * @return        The set of all subscriptions currently owned by this person.
	 */
	public Set<Subscription> get(Long person) {
		return new HashSet<>(subscriptions.getOrDefault(person, new HashSet<>()));
	}

	/**
	 * Updates a subscription in the current {@link SubscriptionContainer}. This method may update existing
	 * subscriptions by deleting one of them if the cache, governed by the size configuration given by
	 * {@link PushProperties#getMaxSubscriptionsPerPerson()}, overflows or by updating the most recent use
	 * time for a subscription.
	 *
	 * @param dto The DTO representing the subscription to update.
	 */
	public synchronized void update(SubscriptionCreateDTO dto) {
		// Create the subscription and set its last used time
		Subscription subscription = dto.apply();
		subscription.setLastUsed(LocalDateTime.now());

		// Get the subscription set for the current person
		var subscriptionSet = subscriptions.computeIfAbsent(
				subscription.getPerson(), e -> new HashSet<>());

		// Remove any old versions of the subscription and add the latest subscription
		subscriptionSet.removeIf(s -> Objects.equals(s.getEndpoint(), subscription.getEndpoint()));
		subscriptionSet.add(subscription);

		// Remove any overflow of the subscription set
		if (subscriptionSet.size() >= properties.getMaxSubscriptionsPerPerson()) {
			subscriptionSet.stream()
					.min(Comparator.comparing(Subscription::getLastUsed))
					.ifPresent(subscriptionSet::remove);
		}
	}

}
