#include <stdint.h>
#include <stdio.h>
#include <strings.h>

#include "fs_private.h"

enum {
    FS_LOOKUP_PATH_BUFFER_SIZE = 1024,
};

void *FS_GetDataForFile(const char *base, const char *path, const char *extension)
{
    char lookupPath[FS_LOOKUP_PATH_BUFFER_SIZE];
    searchpath_t *searchpath;
    pack_t *pack;
    fileInPack_t **packHashTable;
    fs_dir_file_t **dirHashTable;
    uint32_t hash;
    fileInPack_t *packFile;
    fs_dir_file_list_t *dirList;
    fs_dir_file_t *dirFile;

    sprintf(lookupPath, "%s/%s%s", base, path, extension);
    for (searchpath = fs_lookup_searchpaths;
         searchpath != NULL;
         searchpath = FS_SearchpathNext(searchpath)) {
        if (FS_UseSearchPath(searchpath) == 0 || searchpath->pack == NULL) {
            continue;
        }

        pack = searchpath->pack;
        hash = FS_HashFileName(lookupPath, pack->hashSize);
        packHashTable = pack->hashTable;

        for (packFile = packHashTable[hash]; packFile != NULL;
             packFile = packFile->next) {
            if (FS_FilenameCompare(packFile->name, lookupPath) == 0) {
                return &packFile->basename;
            }
        }
    }

    sprintf(lookupPath, "%s%s", path, extension);
    for (dirList = fs_lookup_dir_file_lists;
         dirList != NULL; dirList = FS_DirFileListNext(dirList)) {
        if (strcasecmp(dirList->path, base) != 0) {
            continue;
        }

        hash = FS_HashFileName(lookupPath, dirList->hashSize);
        dirHashTable = dirList->hashTable;

        for (dirFile = dirHashTable[hash]; dirFile != NULL;
             dirFile = dirFile->next) {
            if (FS_FilenameCompare(dirFile->name, lookupPath) == 0) {
                return dirFile;
            }
        }
    }

    return NULL;
}
