/*
 * 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 java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.OptionalDouble;

import javax.persistence.Embedded;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import lombok.*;
import lombok.experimental.SuperBuilder;
import nl.tudelft.queue.model.LabRequest;
import nl.tudelft.queue.model.Request;
import nl.tudelft.queue.model.TimeSlot;
import nl.tudelft.queue.model.embeddables.SlottedLabConfig;

@Data
@SuperBuilder
@MappedSuperclass
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public abstract class AbstractSlottedLab<TS extends TimeSlot> extends Lab {
	/**
	 * The embedded configuration of time slots within this lab.
	 */
	@NotNull
	@Embedded
	@Builder.Default
	private SlottedLabConfig slottedLabConfig = new SlottedLabConfig();

	/**
	 * Whether students can grab slots after the slot is finished. This option should be off by default as it
	 * is often undesirable. When turned on, previously finished slots may be selected after their closing
	 * time.
	 */
	@NotNull
	@Builder.Default
	private Boolean canSelectDueSlots = false;

	/**
	 * The time (in minutes) before a slot that the requests in the time slot can already be taken by student
	 * assistants. This time should be carefully considered when configuring a lab, because it is currently
	 * not shown clearly to teaching assistants whether it was possible to get an earlier request than the one
	 * they got. 10 minutes for 20 minute slots is often too much to distinguish and will leave TAs too busy.
	 */
	@Min(0)
	@NotNull
	@Builder.Default
	private Integer earlyOpenTime = 0;

	/**
	 * @return The mapped list of TimeSlots that are created for this lab.
	 */
	public abstract List<TS> getTimeSlots();

	public boolean allowsRequest(LabRequest request) {
		return request.getTimeSlot() != null &&
				((canSelectDueSlots && !request.getTimeSlot().isFull())
						|| request.getTimeSlot().canTakeSlot())
				&&
				super.allowsRequest(request);
	}

	/**
	 * Is the lab in consecutive filling mode.
	 *
	 * @return true iff lab is in consecutive filling mode, false otherwise.
	 */
	public boolean isConsecutive() {
		return slottedLabConfig.isConsecutive();
	}

	@Override
	public OptionalDouble currentWaitingTime() {
		var labEndTime = getSessionDto().getEndTime();
		var slots = getTimeSlots().stream();
		OptionalDouble baseWaitTime;
		LocalDateTime effectiveEndTime;

		if (labEndTime.isBefore(now())) {
			effectiveEndTime = labEndTime;
			baseWaitTime = OptionalDouble.of(0);
		} else {
			slots = slots.filter(ts -> ts.getSlot().getOpensAt().isBefore(now()));
			effectiveEndTime = now();
			baseWaitTime = OptionalDouble.empty();
		}

		// Find the last started timeslot with pending requests, if any.
		// Otherwise, find the last started timeslot with requests.
		// Then pick the first created pending request, if any. Otherwise, pick the first created request.
		return slots.max(Comparator.<TimeSlot>comparingInt(ts -> ts.hasPendingRequests() ? 1 : -1)
				.thenComparingInt(ts -> ts.getRequests().size() > 0 ? 1 : -1)
				.thenComparing(ts -> ts.getSlot().getOpensAt()))
				.stream()
				.flatMap(ts -> ts.getRequests().stream())
				.max(Comparator
						.<LabRequest>comparingInt(r -> r.getEventInfo().getStatus().isPending() ? 1 : -1)
						.thenComparing(Comparator.nullsFirst(Comparator
								.<LabRequest, LocalDateTime>comparing(Request::getCreatedAt)
								.reversed())))
				.map(r -> r.sensibleWaitingTime(effectiveEndTime))
				.orElse(baseWaitTime);

	}
}
