#include "fileman.h"


static int global_arr_size = FILE_ARR_SIZE;

//int global_arr_size = 5;

int findFileCount(char* directory) {
    int fileCount=0;
    DIR* d;
    struct dirent* dir;
    d = opendir(directory);

    if (d) {
        while ((dir = readdir(d)) != NULL) {
//          mvwprintw(win,startRow,startCol,"%s",dir->d_name);
		if ((strcmp(dir->d_name,".") != 0) && (strcmp(dir->d_name,"..") != 0)) {
			fileCount++;
		}
            //startRow++;
        }
    closedir(d);
    }
	return fileCount;
}



void addFiles(char* directory, char** list,int start,int end) {
//	for (int i=0;i<FILE_ARR_SIZE;i++) {

	for (int i=0;i<global_arr_size;i++) {
		*(list+i) = '\0';
	}

	DIR* d2;



//	int fileNum = findFileCount(directory);

//	int lengthOfArr = FILE_SIZE * sizeof(char *);

//	list = realloc(list,lengthOfArr);

//	int lengthOfArr = 2000;

//	if (lengthOfArr < 200) {
//		printf("%d\n",lengthOfArr);
//		abort();
//	}
	
	struct dirent* dir2;
	int count=0;
//	printw("bruh");
	d2 = opendir(directory);
	if (d2) {
        	for (int i=0;i<start;i++) {
        		dir2 = readdir(d2);
        	}
        	
        	while ((dir2 = readdir(d2)) != NULL && count<end) {
			if ((strcmp(dir2->d_name,".") != 0) && (strcmp(dir2->d_name,"..") != 0)) {
//	        		list[count] = dir2->d_name;
				*(count+list) = dir2->d_name;
		        	count++;
			}
			
			if (count >= global_arr_size) {
				global_arr_size += FILE_ARR_SIZE;
				list = realloc(list,(sizeof(char *) * global_arr_size));
//				abort();
	//			printf("%d\n",lengthOfArr);
	//			abort();
			}		

	        }
		closedir(d2);
	}
}



/*void removeDirFromPath (char** ptrPath) {
	int slashLoc = 0;
	int counter = 0;
	for (int i=strlen(*ptrPath)-1;i>=0;i--) {
		if (counter==1)
			slashLoc = i;
		if (*ptrPath[i] == '/')
			counter++;
	}
	for (int i=slashLoc+1;i<strlen(*ptrPath);i++){
		if (*ptrPath[i] != '\0')
			*ptrPath[i] = '\0';

	}
}*/


void removeDirFromPath (char* ptrPath) {
        int slashLoc = 0;
        int counter ;
	if (isFile(ptrPath)) {
		counter=1;
	} else {
		counter = 0;
	}

        for (int i=strlen(ptrPath)-1;i>=0;i--) {
                if (counter==1 && *(ptrPath+i) == '/')
                        slashLoc = i;
                if (*(ptrPath+i) == '/')
                        counter++;
        }
        for (int i=slashLoc+1;i<strlen(ptrPath);i++){
                if (*(ptrPath+i) != '\0')
                        *(ptrPath+i) = '\0';

        }
}

void addSlash(char* ptrPath) {
	for (int i=strlen(ptrPath)-1;i>=0;i--) {
		if ((*(ptrPath+i) != '\0') && (*(ptrPath+i) != '/')) {
			*(ptrPath+i+1) = '/';
			return;
		}
	}

}


bool isFile(char *ptrDir) {
	if (!(fileExists(ptrDir))) {
		return true;
	}
	struct stat pathstat;
	stat(ptrDir,&pathstat);
	return S_ISREG(pathstat.st_mode);
}

bool fileExists(char *ptrDir) {
	return access(ptrDir,F_OK) == 0;
}
