package speiger.src.coreengine.utils.io.finders;

import java.io.File;

import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.util.nfd.NFDPathSet;
import org.lwjgl.util.nfd.NativeFileDialog;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.collections.objects.sets.ObjectSortedSet;

public class NativeFileFinder implements IFileFinder
{
	public static final IFileFinder INSTANCE = new NativeFileFinder();
	
	@Override
	public ObjectList<File> build(int flags, String startPath, ObjectSortedSet<String> validFormats, String description)
	{
		ObjectList<File> files = new ObjectArrayList<>();
		if((flags & SAVE) != 0)
		{
			try(MemoryStack stack = MemoryStack.stackPush())
			{
				PointerBuffer output = stack.mallocPointer(1);
				if(NativeFileDialog.NFD_SaveDialog(toFileFormat(validFormats), startPath, output) == NativeFileDialog.NFD_OKAY)
				{
					File file = new File(output.getStringUTF8());
					if(file.getName().lastIndexOf(".") == -1) file = new File(file.getParent(), file.getName()+"."+validFormats.first());
					files.add(file);
				}
			}
		}
		else if((flags & FOLDER) != 0)
		{
			try(MemoryStack stack = MemoryStack.stackPush())
			{
				PointerBuffer output = stack.mallocPointer(1);
				if(NativeFileDialog.NFD_PickFolder(startPath, output) == NativeFileDialog.NFD_OKAY)
				{
					files.add(new File(output.getStringUTF8()));
				}
			}
		}
		else if((flags & MULTI_FILE) != 0)
		{
			try(MemoryStack stack = MemoryStack.stackPush())
			{
				NFDPathSet paths = NFDPathSet.mallocStack(stack);
				if(NativeFileDialog.NFD_OpenDialogMultiple(toFileFormat(validFormats), startPath, paths) == NativeFileDialog.NFD_OKAY)
				{
					int size = (int)NativeFileDialog.NFD_PathSet_GetCount(paths);
					for(int i = 0;i<size;i++)
					{
						files.add(new File(NativeFileDialog.NFD_PathSet_GetPath(paths, i)));
					}
				}
			}
		}
		else
		{
			try(MemoryStack stack = MemoryStack.stackPush())
			{
				PointerBuffer output = stack.mallocPointer(1);
				if(NativeFileDialog.NFD_OpenDialog(toFileFormat(validFormats), startPath, output) == NativeFileDialog.NFD_OKAY)
				{
					files.add(new File(output.getStringUTF8()));
				}
			}
		}
		return files;
	}
}
