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

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import nl.tudelft.queue.properties.QueueProperties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class AdminService {

	@Autowired
	private QueueProperties qp;

	/**
	 * Stores a file in the maps folder
	 *
	 * @param  file        The mulitpart file to be stored
	 * @param  fileName    The name this file should get
	 * @throws IOException Thrown when it is not possible to write to the designated location
	 */
	public void uploadFile(MultipartFile file, String fileName) throws IOException {
		Path mapStoragePath = Paths.get(qp.getStaticallyServedPath(), "maps");
		File uploadLocation = mapStoragePath.toFile();
		String filteredFileName = fileName.replaceAll("../", "");
		var path = Paths.get(mapStoragePath.toString(), filteredFileName);
		File savedFile = Files.createFile(path).toFile();
		if (!uploadLocation.exists() && !uploadLocation.mkdirs()) {
			throw new IOException("Can not create path for storing maps: " + uploadLocation);
		}
		Files.copy(file.getInputStream(), savedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
	}

	/**
	 * Gets the filename of a room map.
	 *
	 * @return The filename corresponding to the map of the given room.
	 */
	public String getRoomFileName(Long roomId) {
		Path mapStoragePath = Paths.get(qp.getStaticallyServedPath(), "maps");
		try (var files = Files.walk(mapStoragePath, 1)) {
			return files
					.map(p -> p.getFileName().toString())
					.filter(name -> name.matches("room-" + roomId + "\\.\\w+"))
					.findFirst().orElse(null);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Gets all rooms that have a map stored.
	 *
	 * @return The set of room IDs with a map
	 */
	public Set<Long> getRoomsWithMaps() {
		Path mapStoragePath = Paths.get(qp.getStaticallyServedPath(), "maps");
		Pattern pattern = Pattern.compile("room-(\\d+)\\.\\w+");
		try (var files = Files.walk(mapStoragePath, 1)) {
			return files
					.map(p -> p.getFileName().toString())
					.map(pattern::matcher)
					.filter(Matcher::matches)
					.map(matcher -> Long.parseLong(matcher.group(1)))
					.collect(Collectors.toSet());
		} catch (IOException e) {
			e.printStackTrace();
			return Collections.emptySet();
		}
	}

}
