/*
 * 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.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.modelmapper.internal.util.Callable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import nl.tudelft.queue.properties.QueueProperties;

@Service
public class FileService {
	@Autowired
	private QueueProperties qp;

	/**
	 * Writes a single temporary resource under the given file name in the temporary files directory.
	 *
	 * @param  filename    The name of the file to write.
	 * @param  f           The producer of the string to write to file.
	 * @return             The resource representing the written temporary file.
	 * @throws IOException when something goes wrong writing or reading to/from file.
	 */
	public Resource writeTempResource(String filename, Callable<String> f) throws IOException {
		String filteredFileName = filename.replaceAll("../", "");
		var path = Paths.get(qp.getTempFileDirectory(), filteredFileName);
		if (!path.toFile().exists()) {
			Files.createDirectories(Paths.get(qp.getTempFileDirectory()));
			Files.write(path, f.call().getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW);
		}

		return new FileSystemResource(path);
	}
}
