#include <fat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/dir.h>
#include <string.h>

#include "../io.h"

BROWSERFILEINFO files[MAX_ENTRY];
BROWSERFILEINFO *sortfiles[MAX_ENTRY];
int nfiles;

// extension structures
const struct {
	char *szExt;
	int nExtId;
} stExtentions[] = {
	{"gb",EXT_GB},
	{"gbc",EXT_GB},
	{"sgb",EXT_GB},
	{"gz",EXT_GZ},
	{"zip",EXT_ZIP},
	{"tch",EXT_TCH},
	{NULL, EXT_UNKNOWN}
};

unsigned long io_get_extension(const char *szFilePath)
{
	char *pszExt;
	
	pszExt = strrchr(szFilePath, '.');
	if (pszExt) {
		pszExt++;
		int i;
		for (i=0; stExtentions[i].nExtId!=EXT_UNKNOWN; i++){
			if (!stricmp(stExtentions[i].szExt,pszExt)){
				return stExtentions[i].nExtId;
			}
		}
	}
	
	return EXT_UNKNOWN;
}

int io_file_compare(BROWSERFILEINFO *a, BROWSERFILEINFO *b)
{
	if(a->attr == b->attr )
		return strcmp(a->path, b->path);

	if(a->attr)	
		return -1;
	else
		return 1;
}
void io_sort_files(BROWSERFILEINFO **a, int left, int right)
{
	BROWSERFILEINFO *tmp, *pivot;
	int i, p;
	
	if (left < right) {
		pivot = a[left];
		p = left;
		for (i=left+1; i<=right; i++) {
			if (io_file_compare(a[i],pivot)<0){
				p=p+1;
				tmp=a[p];
				a[p]=a[i];
				a[i]=tmp;
			}
		}
		a[left] = a[p];
		a[p] = pivot;
		io_sort_files(a, left, p-1);
		io_sort_files(a, p+1, right);
	}
}
int io_load_folder_files(const char *path, unsigned long ext)
{
	DIR_ITER* dp = diropen( path );
	if(!dp)
		return -1;

	char filename[MAXPATHLEN];
	struct stat fstat;
	int root=1;
	
	nfiles = 0;
	
	 while( dirnext(dp, filename, &fstat) == 0 )
	 {
		 if ((io_get_extension(filename) & ext) || fstat.st_mode & S_IFDIR)
		 {
			if (strcmp(filename, ".")==0)
				continue;
			if (strcmp(path, "/")==0 && strcmp(filename, "..")==0)
				continue;
			//memset(&files[nfiles], 0x00, sizeof(BROWSERFILEINFO));
			sprintf(files[nfiles].name, "%s", filename);
			sprintf(files[nfiles].path, "%s/%s", path, filename);
			files[nfiles].size   = fstat.st_size;
			files[nfiles].attr   = (fstat.st_mode & S_IFDIR) ? 1 : 0;
			sortfiles[nfiles] = &files[nfiles];
			++nfiles;
		 }
     }
        
    dirclose(dp);
	
	if(root)
		io_sort_files(sortfiles, 0, nfiles-1);
	else
		io_sort_files(sortfiles+1, 0, nfiles-2);

    return nfiles;
}
