#include <midas.h>

#ifdef _WIN32
#include <windows.h>
#endif

struct direntry {
	struct ppr_dirent d;
	struct ppr_stat	  s;
	char*		  path;
};

static int sort_de(const void* _a, const void* _b) {
	struct direntry* a = (struct direntry*)_a;
	struct direntry* b = (struct direntry*)_b;

	if(PPR_S_ISDIR(a->s.st_mode) && !PPR_S_ISDIR(b->s.st_mode)) return -1;
	if(!PPR_S_ISDIR(a->s.st_mode) && PPR_S_ISDIR(b->s.st_mode)) return 1;

	return strcmp(a->d.d_name, b->d.d_name);
}

static void dir_recursion(const char* path, const char* path2, void* tv) {
	PPR_DIR*	   dir;
	struct ppr_dirent* d;
	struct direntry*   de = NULL;
	int		   i;

	tv = MwTreeViewAdd(fileview, tv, NULL, path2);
	if(path != path2) MwTreeViewSetOpened(fileview, tv, 0);
	if((dir = ppr_opendir(path)) != NULL) {
		while((d = ppr_readdir(dir)) != NULL) {
			struct direntry new_de;

			if(d->d_name[0] == '.') continue;

			new_de.path = ppr_strvacat(path, "/", d->d_name, NULL);
			new_de.d    = *d;
			ppr_stat(new_de.path, &new_de.s);
			arrput(de, new_de);
		}
	}

	if(de != NULL) {
		qsort(de, arrlen(de), sizeof(*de), sort_de);
		for(i = 0; i < arrlen(de); i++) {
			char* p = ppr_strvacat(de[i].d.d_name, PPR_S_ISDIR(de[i].s.st_mode) ? "/" : "", NULL);

			dir_recursion(de[i].path, p, tv);

			free(p);

			free(de[i].path);
		}
		arrfree(de);
	}
}

void dir_scan(const char* dir) {
	char  real[2048];
	void* e;

#ifdef _WIN32
	GetFullPathName(dir, 2048, real, NULL);
#else
	realpath(dir, real);
#endif

	dir_recursion(real, real, NULL);
}
