/*
 * 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.util.ArrayList;
import java.util.List;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import nl.tudelft.queue.dto.view.LabViewDTO;
import nl.tudelft.queue.model.TimeSlot;
import nl.tudelft.queue.model.embeddables.SlottedLabConfig;
import nl.tudelft.queue.model.labs.AbstractSlottedLab;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class AbstractSlottedLabViewDTO<D extends AbstractSlottedLab<?>> extends LabViewDTO<D> {
	private SlottedLabConfig slottedLabConfig;

	private List<TimeSlot> timeSlots = new ArrayList<>();

	@NotNull
	private Boolean canSelectDueSlots = false;

	@Min(0)
	@NotNull
	private Integer earlyOpenTime = 0;

	private int slotsOccupied;

	private int maxSlots;

	/**
	 * @return Whether the slot selection for this lab is open.
	 */
	public boolean isSlotSelectionOpen() {
		return getStatus().isOpenToEnqueueing();
	}

	/**
	 * @param  n The number of slices to divide the time slots in.
	 * @return   Each of the slices as a list of time slots in a list.
	 */
	public List<List<TimeSlot>> sliceTimeSlotsVertical(int n) {
		int div = timeSlots.size() / n;
		int rem = timeSlots.size() % n;

		List<TimeSlot> temp = new ArrayList<>();
		List<List<TimeSlot>> result = new ArrayList<>();

		for (TimeSlot ts : timeSlots) {
			if (temp.size() < div) {
				temp.add(ts);
			} else if (rem > 0) {
				temp.add(ts);
				rem--;

				result.add(temp);
				temp = new ArrayList<>();
			} else {
				result.add(temp);
				temp = new ArrayList<>();
				temp.add(ts);
			}
		}

		if (!temp.isEmpty()) {
			result.add(temp);
		}

		return result;
	}

	@Override
	public void postApply() {
		super.postApply();
		maxSlots = this.data.getTimeSlots().stream().mapToInt(TimeSlot::getCapacity).sum();
		slotsOccupied = this.data.getTimeSlots().stream().mapToInt(TimeSlot::countSlotsOccupied).sum();
	}
}
