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

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import nl.tudelft.labracore.api.dto.RoomDetailsDTO;
import nl.tudelft.queue.dto.view.QueueSessionViewDTO;
import nl.tudelft.queue.model.SelectionRequest;
import nl.tudelft.queue.model.embeddables.CapacitySessionConfig;
import nl.tudelft.queue.model.labs.CapacitySession;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class CapacitySessionViewDTO extends QueueSessionViewDTO<CapacitySession> {
	private CapacitySessionConfig capacitySessionConfig;

	private int capacity;

	/**
	 * @return Whether the current time is after the selection at time.
	 */
	public boolean isAfterSelection() {
		return capacitySessionConfig.getSelectionAt().isBefore(LocalDateTime.now());
	}

	public Map<RoomDetailsDTO, Integer> selectedOrPendingCountsPerRoom() {
		Map<Long, RoomDetailsDTO> rooms = getSession().getRooms().stream()
				.collect(Collectors.toMap(RoomDetailsDTO::getId, Function.identity()));
		Map<RoomDetailsDTO, Integer> roomSelects = new TreeMap<>(
				Comparator.comparing(r -> r.getBuilding().getName() + r.getName()));
		roomSelects.putAll(getSession().getRooms().stream()
				.collect(Collectors.toMap(Function.identity(), _r -> 0)));

		for (SelectionRequest r : data.getRequests()) {
			var status = r.getEventInfo().getStatus();
			if ((status.isSelected() || status.isPending()) &&
					r.getRoom() != null && rooms.containsKey(r.getRoom())) {
				roomSelects.computeIfPresent(rooms.get(r.getRoom()), (_r, count) -> count + 1);
			}
		}

		return roomSelects;
	}
}
