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

import java.util.Objects;
import java.util.stream.Stream;

import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;
import nl.tudelft.labracore.api.ModuleDivisionControllerApi;
import nl.tudelft.labracore.api.dto.StudentGroupDetailsDTO;
import nl.tudelft.queue.cache.ClusterCacheManager;
import nl.tudelft.queue.cache.PersonCacheManager;
import nl.tudelft.queue.cache.StudentGroupCacheManager;
import nl.tudelft.queue.model.LabRequestConstraint;
import nl.tudelft.queue.model.Request;
import nl.tudelft.queue.model.constraints.ClusterConstraint;
import nl.tudelft.queue.model.constraints.ModuleDivisionConstraint;
import nl.tudelft.queue.model.embeddables.LabRequestConstraints;

@Service
@AllArgsConstructor
public class LabRequestConstraintService {

	private final StudentGroupCacheManager studentGroupCacheManager;

	private final PersonCacheManager personCacheManager;

	private final ModuleDivisionControllerApi moduleDivisionControllerApi;

	private final ClusterCacheManager clusterCacheManager;

	public boolean canCreateRequest(LabRequestConstraints constraints, Long personId) {
		return constraints.toList().stream().allMatch(c -> canCreateRequest(c, personId));
	}

	public boolean canCreateRequest(LabRequestConstraint constraint, Long personId) {
		if (constraint instanceof ModuleDivisionConstraint) {
			return canCreateRequest((ModuleDivisionConstraint) constraint, personId);
		} else if (constraint instanceof ClusterConstraint) {
			return canCreateRequest((ClusterConstraint) constraint, personId);
		} else {
			throw new IllegalArgumentException(
					"Unsupported constraint type: " + constraint.getClass().getSimpleName());
		}
	}

	public boolean canCreateRequest(ModuleDivisionConstraint constraint, Long personId) {
		Stream<Long> studentGroups = studentGroupCacheManager.getByPerson(personId).stream()
				.map(StudentGroupDetailsDTO::getId);

		return studentInDivision(constraint, personId) || studentGroupInDivision(constraint,
				studentGroups);
	}

	/**
	 * Checks whether the given request is allowed according to the constraints in this object.
	 *
	 * @param  constraints The constraints for which to check.
	 * @param  request     The request to check for whether it is allowed to be posted.
	 * @return             Whether the given request should be allowed.
	 */
	public boolean allowsRequest(LabRequestConstraints constraints, Request<?> request) {
		return constraints.toList().stream().allMatch(c -> allowsRequest(c, request));
	}

	public boolean allowsRequest(ModuleDivisionConstraint constraint, Request<?> request) {
		return studentInDivision(constraint, request.getRequester())
				|| studentGroupInDivision(constraint, Stream.of(request.getStudentGroup()));
	}

	public boolean allowsRequest(LabRequestConstraint constrains, Request<?> request) {
		return canCreateRequest(constrains, request.getRequester());
	}

	private boolean studentGroupInDivision(ModuleDivisionConstraint constraint,
			Stream<Long> studentGroups) {
		return studentGroups.map(s -> studentGroupCacheManager.get(s).orElseThrow())
				.anyMatch(sg -> sg.getDivision() != null
						&& constraint.getDivisions().contains(sg.getDivision().getId()));
	}

	private boolean studentInDivision(ModuleDivisionConstraint constraint, Long personId) {
		var person = personCacheManager.get(personId).orElseThrow();
		return constraint.getDivisions().stream()
				.anyMatch(d -> Objects
						.requireNonNull(moduleDivisionControllerApi.getPeopleInDivision(d).block())
						.getPeople().contains(person));
	}

	public boolean canCreateRequest(ClusterConstraint constraint, Long personId) {
		return clusterCacheManager.getAndHandle(constraint.getClusters().stream(),
				clusterID -> constraint.getClusters().remove(clusterID)).stream()
				.anyMatch(cluster -> cluster.getPeople().stream()
						.anyMatch(p -> Objects.equals(p.getId(), personId)));
	}
}
