/* stdlib/file.c */

#ifndef _WIN32
#error "Only implemented on _WIN32"
#endif

#include <stdio.h>

#include <Windows.h>

#include "../rtl/pexl_rtl.h"

PUBLIC_OBJECT stdcall PXString* pxl_lib_file_getcontents(PXString* path) {
	
	PXString *ret = (PXString*)pxo_string_new();
	
	if (path == NULL) {
		return ret; 
	}
	
	FILE *f = fopen(path->buff, "rb");
	if (f == NULL) {
		return ret;
	}
	
	fseek(f, 0, SEEK_END);
	PXRegister len = ftell(f);
	fseek(f, 0, SEEK_SET);
	
	ret->buff = (unsigned char*) pxl_rtl_malloc(len);
	fread(ret->buff, len, 1, f);
	
	fclose(f);
	
	ret->buffsize = len;
	ret->strlen   = len;
	
	return ret;
}

PUBLIC_OBJECT stdcall PXRegister pxl_lib_file_exists(PXString* path) {

	FILE *file = fopen(path->buff, "r");
	
	if (file == NULL) {
		return 0; /* zero is falsey */
		
	} else {
		fclose(file);
		return 1; /* positive ints are truthy */
		
	}
}

PUBLIC_OBJECT stdcall PXVector* pxl_lib_file_scandir(PXString* path) {
	
	PXVector* ret = (PXVector*)pxl_vec_init();
	
	/* Win32 structs */
	
	WIN32_FIND_DATA wfd = {0};
	HANDLE hFind = FindFirstFile(path->buff, &wfd);
	
	if (hFind != INVALID_HANDLE_VALUE) {
		
		do {
				
			/* String */
			
			PXString* item = (PXString*) pxo_string_new();
			
			size_t filename_len = strlen( wfd.cFileName ); /* inline */ 
			
			item->buff     = (unsigned char*) pxl_rtl_malloc( filename_len );
			item->buffsize = filename_len;
			item->strlen   = filename_len;
			
			memcpy( item->buff, wfd.cFileName, filename_len ); /* inline */ 
			
			/* Push to vector */
			
			pxl_vec_push( ret , (PXRegister)item );
			
		} while ( FindNextFile(hFind, &wfd) != 0 );
		
	}
	
	FindClose( hFind );
	
	return ret;
}
