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

import javax.transaction.Transactional;

import nl.tudelft.labracore.api.CourseControllerApi;
import nl.tudelft.labracore.api.EditionControllerApi;
import nl.tudelft.labracore.api.ProgramControllerApi;
import nl.tudelft.labracore.api.dto.*;
import nl.tudelft.queue.model.QueueEdition;
import nl.tudelft.queue.repository.QueueEditionRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * A service that runs during startup. This startup procedure goes through all editions and unhides them in
 * Queue.
 */
@Service
@ConditionalOnExpression("#{'${queue.startup.unhide-all-editions}' == 'true'}")
public class UnhideEditionsService {
	private static final Logger logger = LoggerFactory.getLogger(UnhideEditionsService.class);

	@Autowired
	private QueueEditionRepository qer;

	@Autowired
	private EditionControllerApi eApi;

	@Autowired
	private CourseControllerApi cApi;

	@Autowired
	private ProgramControllerApi pApi;

	@Transactional
	@EventListener(ApplicationReadyEvent.class)
	public void unhideAllEditions() {
		// Going by programme > course > edition to not request to much data
		for (ProgramSummaryDTO programme : pApi.getAllPrograms().collectList().block()) {
			logger.info("Unhiding courses of programme: " + programme.getName());
			for (CourseSummaryDTO course : cApi.getAllCoursesByProgram(programme.getId()).collectList()
					.block()) {
				for (EditionDetailsDTO edition : eApi.getAllEditionsByCourse(course.getId()).collectList()
						.block()) {
					qer.findById(edition.getId()).ifPresentOrElse(
							e -> {
								e.setHidden(false);
								qer.save(e);
							},
							() -> qer.save(QueueEdition.builder().id(edition.getId()).hidden(false).build()));
				}
			}
		}
	}
}
