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;

public class FileContentPack implements ContentPack {
	private final String id;
	private final Path base;

	public FileContentPack(@NotNull String id, @NotNull Path base) {
		this.id = id;
		this.base = base;
	}

	@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();
	}

	@Override
	public Resource getResource(@NotNull String location) {
		File file = base.resolve(Path.of(location)).toFile();
		if (file.isFile()) {
			return new FileResource(Util.pathToId(id, location), file);
		}
		return null;
	}

	@Override
	@NotNull
	public String getId() {
		return id;
	}
}
