package de.siphalor.was.content.pack;

import de.siphalor.was.content.resource.FileResource;
import de.siphalor.was.content.resource.Resource;
import de.siphalor.was.util.Util;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * An implementation of a {@link ContentPack} as a directory.
 */
public class FileContentPack implements ContentPack {
	/**
	 * The pack's id
	 */
	private final String id;
	/**
	 * The base path where the pack is located
	 */
	private final Path base;

	/**
	 * Constructs a new file content pack.
	 * @param id The pack id
	 * @param base The path to the pack directory
	 */
	public FileContentPack(@NotNull String id, @NotNull Path base) {
		this.id = id;
		this.base = base;
	}

	/**
	 * Gets all of the resources in the specified location with the specified type
	 * @param location The location to search
	 * @param type The file extension
	 * @return Returns a stream of these resources
	 */
	@Override
	public @NotNull Stream<Resource> getResources(@NotNull String location, @NotNull String type) {
		final String extension = "." + type;
		Path dir = base.resolve(Path.of(location));
		if (dir.toFile().isDirectory()) {
			try {
				return Files.find(dir, Integer.MAX_VALUE, (path, attributes) -> attributes.isRegularFile() && path.getFileName().getName(0).toString().endsWith(extension)).map(path ->
						new FileResource(Util.pathToId(id, dir.relativize(path).toString()), path.toFile())
				);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return Stream.empty();
	}

	/**
	 * Gets a single file resource with the given identifier.
	 * @param identifier The resource identifier
	 * @return Returns the file resource or <code>null</code> if it doesn't exist
	 */
	@Override
	public Resource getResource(@NotNull String identifier) {
		File file = base.resolve(Path.of(identifier)).toFile();
		if (file.isFile()) {
			return new FileResource(Util.pathToId(id, identifier), file);
		}
		return null;
	}

	/**
	 * Get the pack's id
	 * @return The pack's id
	 */
	@Override
	@NotNull
	public String getId() {
		return id;
	}
}
