/*
 * 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.model.labs;

import static java.time.LocalDateTime.now;
import static nl.tudelft.librador.SpringContext.getBean;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import lombok.*;
import lombok.experimental.SuperBuilder;
import nl.tudelft.queue.cache.SessionCacheManager;
import nl.tudelft.queue.model.LabRequest;
import nl.tudelft.queue.model.QueueSession;
import nl.tudelft.queue.model.Request;
import nl.tudelft.queue.model.embeddables.AllowedRequest;
import nl.tudelft.queue.model.enums.CommunicationMethod;
import nl.tudelft.queue.model.enums.OnlineMode;
import nl.tudelft.queue.model.enums.RequestType;
import nl.tudelft.queue.model.misc.Presentation;
import nl.tudelft.queue.service.LabService;

import org.hibernate.validator.constraints.UniqueElements;

@Data
@Entity
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public abstract class Lab extends QueueSession<LabRequest> {

	/**
	 * The communication method that will be used for the lab. Online meetings disregard this.
	 */
	@NotNull
	@Enumerated(EnumType.STRING)
	private CommunicationMethod communicationMethod;

	/**
	 * The grace period at the end of lab in minutes. This is a time where no further requests can be added to
	 * the request list, but teaching assistants and teachers may still take and answer requests.
	 */
	@Min(0)
	@NotNull
	@Max(180)
	@Builder.Default
	private Integer eolGracePeriod = 15;

	/**
	 * The request types that are allowed within this lab.
	 */
	@NotEmpty
	@UniqueElements
	@Builder.Default
	@ElementCollection
	private Set<AllowedRequest> allowedRequests = new HashSet<>();

	/**
	 * The online options available for the lab. Currently only Jitsi
	 */
	@NotNull
	@UniqueElements
	@Builder.Default
	@ElementCollection
	private Set<OnlineMode> onlineModes = new HashSet<>();

	@NotNull
	@Builder.Default
	private Boolean isBilingual = false;

	@NotNull
	@Builder.Default
	private Boolean enableExperimental = false;

	@OneToOne(mappedBy = "lab")
	@ToString.Exclude
	@EqualsAndHashCode.Exclude
	private Presentation presentation;

	/**
	 * Sets the allowed request types for this lab using a map of assignments to the request types that are
	 * allowed to be created for that assignment.
	 *
	 * @param requestTypes The mapping of assignments to request types from which to read allowed requests.
	 */
	public void setAllowedRequestsFromMap(Map<Long, Set<RequestType>> requestTypes) {
		this.setAllowedRequests(requestTypes.entrySet().stream()
				.flatMap(e -> {
					if (e.getValue() == null) {
						return Stream.empty();
					} else {
						return e.getValue().stream()
								.filter(Objects::nonNull)
								.map(v -> new AllowedRequest(e.getKey(), v));
					}
				})
				.collect(Collectors.toSet()));
	}

	/**
	 * Gets the current waiting time for the longest waiting request in this lab.
	 *
	 * @return The current waiting time
	 */
	public abstract OptionalDouble currentWaitingTime();

	/**
	 * Gets the average waiting time experienced by students in this lab over the last hour. If the lab is
	 * over, this returns the average waiting time over the entire lab instead.
	 *
	 * @return The average waiting time if one can be calculated, for fresh labs this is empty.
	 */
	public OptionalDouble averageWaitingTime() {
		var labEndTime = getSessionDto().getEndTime();
		if (labEndTime.isBefore(now())) {
			// past session, give average over the session
			return getHandled().stream()
					.flatMapToDouble(r -> r.sensibleWaitingTime(labEndTime).stream())
					.average();
		} else {
			return getHandled().stream()
					.filter(r -> r.getEventInfo().getLastEventAt().isAfter(now().minusHours(1)))
					.flatMapToDouble(r -> r.sensibleWaitingTime().stream())
					.average();
		}
	}

	@Override
	public boolean allowsRequest(Request<?> request) {

		var session = getBean(SessionCacheManager.class).getRequired(getSession(),
				id -> getBean(LabService.class).deleteSession(this));

		return request instanceof LabRequest && super.allowsRequest(request)
				&& allowsRequest((LabRequest) request)
				&& (request.getRoom() == null) ? ((LabRequest) request).getOnlineMode() != null
						: session.getRooms().stream()
								.anyMatch(room -> Objects.equals(room.getId(), request.getRoom()));
	}

	/**
	 * Checks whether the given request is allowed according to the restrictions of this lab.
	 *
	 * @param  request The lab request to check for whether it is allowed to be posted.
	 * @return         Whether the given request should be allowed.
	 */
	protected boolean allowsRequest(LabRequest request) {
		return allowedRequests.contains(AllowedRequest.of(request.getAssignment(), request.getRequestType()));
	}
}
