package speiger.src.coreengine.assets.oldImpl;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.Stream;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.coreengine.assets.AssetLocation;
import speiger.src.coreengine.assets.base.IAsset;
import speiger.src.coreengine.assets.base.IAssetPackage;
import speiger.src.coreengine.utils.collections.iterators.IterableWrapper;

public class FolderAssetPackage implements IAssetPackage {
	Path baseFolder;
	
	public FolderAssetPackage(Path baseFolder) {
		this.baseFolder = baseFolder;
	}
	
	@Override
	public void close() {}
	
	@Override
	public void getModifiedTime(String domain, BiConsumer<AssetLocation, FileTime> accept) {
		try {
			Path start = baseFolder.resolve("assets/").resolve(domain);
			for(Path path : IterableWrapper.wrap(Files.walk(start).filter(Files::isRegularFile).iterator())) {
				accept.accept(AssetLocation.of(domain, start.relativize(path).toString().replace("\\", "/")), Files.getLastModifiedTime(path));
			}
		}
		catch(IOException e) { e.printStackTrace(); }
	}
	
	@Override
	public List<String> getDomains() {
		List<String> domains = new ObjectArrayList<>();
		try(DirectoryStream<Path> dirs = Files.newDirectoryStream(baseFolder.resolve("assets"))) {
			for(Path path : dirs) {
				domains.add(path.getFileName().toString());
			}
		}
		catch(IOException e) { e.printStackTrace(); }
		return domains;
	}
	
	@Override
	public IAsset getAsset(AssetLocation location) {
		Path path = baseFolder.resolve(location.actualLocation());
		return Files.exists(path) ? new SimpleAsset(location, this, path) : null;
	}
	
	@Override
	public void gatherAssets(AssetLocation folder, BiConsumer<AssetLocation, IAsset> result) {
		Path start = baseFolder.resolve(folder.actualLocation());
		if(Files.notExists(start)) return;
		try(Stream<Path> stream = Files.walk(start).filter(Files::isRegularFile)) {
			for(Path path : IterableWrapper.wrap(stream.iterator())) {
				AssetLocation location = folder.subAsset(start.relativize(path).toString().replace("\\", "/"));
				result.accept(location, new SimpleAsset(location, this, path));
			}
		}
		catch(IOException e) {
			e.printStackTrace();
		}		
	}
}