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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import lombok.*;
import lombok.experimental.SuperBuilder;
import nl.tudelft.labracore.api.dto.SessionDetailsDTO;
import nl.tudelft.librador.dto.DTOConverter;
import nl.tudelft.queue.dto.create.TimeSlotCreateDTO;
import nl.tudelft.queue.model.embeddables.Slot;
import nl.tudelft.queue.model.labs.SlottedLab;

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class SlottedLabCreateDTO extends AbstractSlottedLabCreateDTO<SlottedLab> {

	@Builder.Default
	private List<TimeSlotCreateDTO> timeSlots = new ArrayList<>();

	public SlottedLabCreateDTO(SessionDetailsDTO session,
			SlottedLab lab) {
		super(session, lab);
		this.timeSlots = lab.getTimeSlots().stream().map(TimeSlotCreateDTO::new).toList();
	}

	@Override
	public void plusWeeks(Long weeks) {
		super.plusWeeks(weeks);
		timeSlots.forEach(ts -> ts.setSlot(new Slot(ts.getSlot().getOpensAt().plusWeeks(weeks),
				ts.getSlot().getClosesAt().plusWeeks(weeks))));
	}

	@Override
	protected void postApply(SlottedLab data, DTOConverter converter) {
		super.postApply(data, converter);
		data.setTimeSlots(
				timeSlots.stream().map(t -> t.apply(converter)).peek(ts -> ts.setLab(data)).toList());
	}

	@Override
	public void validate() {
		if (!timeSlots.isEmpty()) {
			this.setSlot(new Slot(
					timeSlots.stream().map(ts -> ts.getSlot().getOpensAt()).min(Comparator.naturalOrder())
							.get(),
					timeSlots.stream().map(ts -> ts.getSlot().getClosesAt()).max(Comparator.naturalOrder())
							.get()));
		}
	}

	@Override
	public Class<SlottedLab> clazz() {
		return SlottedLab.class;
	}

}
