package speiger.src.coreengine.platform.input.device;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWDropCallback;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.coreengine.platform.input.device.FileDrop.DropTask;
import speiger.src.coreengine.platform.input.events.FileEvents;
import speiger.src.coreengine.platform.input.window.Window;

public class FileDrop extends AbstractDevice<Void, DropTask> {
	public static final FileDrop INSTANCE = new FileDrop();
	
	@Override
	protected void registerCallbacks(Window window) {
		super.registerCallbacks(window);
		window.addCallback(this::drop, GLFW::glfwSetDropCallback);
	}
	
	private void drop(long windowId, int count, long names) {
		List<Path> paths = new ObjectArrayList<>(count);
		for(int i = 0;i<count;i++) {
			Path path = Path.of(GLFWDropCallback.getName(names, i));
			if(Files.notExists(path)) continue;
			paths.add(path);
		}
		if(paths.isEmpty()) return;
		push(windowId, new DropTask(windowId, paths.toArray(Path[]::new)));
	}
	
	@Override
	public void reset(long windowId) {}
	@Override
	protected Void createData(long windowId) { return null; }
	@Override
	protected void process(DropTask task) {
		int x = Mouse.INSTANCE.x(task.windowId());
		int y = Mouse.INSTANCE.y(task.windowId());
		pushEvent(new FileEvents.Drop(task.windowId(), x, y, task.files()));
	}
	
	public record DropTask(long windowId, Path[] files) {}
}
