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

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.*;
import lombok.experimental.SuperBuilder;
import nl.tudelft.labracore.api.dto.AssignmentIdDTO;
import nl.tudelft.labracore.api.dto.RoomIdDTO;
import nl.tudelft.librador.dto.patch.Patch;
import nl.tudelft.queue.dto.patch.embeddables.LabRequestConstraintsPatchDTO;
import nl.tudelft.queue.model.QueueSession;
import nl.tudelft.queue.model.embeddables.Slot;

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public abstract class QueueSessionPatchDTO<D extends QueueSession<?>> extends Patch<D> {
	private String name;
	private Slot slot;

	@Builder.Default
	private Set<Long> modules = null;

	@Builder.Default
	protected Set<Long> rooms = null;

	@Builder.Default
	private LabRequestConstraintsPatchDTO constraints = new LabRequestConstraintsPatchDTO();

	private String extraInfo;

	@Override
	protected void postApply() {
		constraints.apply(data);
	}

	@Override
	protected void applyManyToManyDominant() {
		updateNonNull(modules, data::setModules);
	}

	@Override
	protected void validate() {
		nonEmpty("modules", modules);
	}

	/**
	 * @return The list of assignments associated with this session, null otherwise.
	 */
	public abstract List<AssignmentIdDTO> assignmentIdDTOs();

	/**
	 * @return The list of room ids if rooms were entered, null otherwise.
	 */
	public List<RoomIdDTO> roomIdDTOs() {
		if (rooms == null) {
			return null;
		}

		return rooms.stream().map(al -> new RoomIdDTO().id(al)).collect(Collectors.toList());
	}

	protected void nonEmpty(String field, Collection<?> set) {
		if (set != null && set.isEmpty()) {
			errors.rejectValue(field, "Field should not be empty");
		}
	}
}
