#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "fs_private.h"

enum {
    FS_MAX_PAKFILES = 1024,
    FS_LOCALIZED_PREFIX_LENGTH = 10,
};

void FS_AddPakFilesForGameDirectory(const char *base, const char *game)
{
    char *sortedPakFiles[FS_MAX_PAKFILES];
    char osPath[FS_OSPATH_SIZE];
    int numPakFiles;
    char **pakFiles;
    int index;
    qboolean localized;
    int32_t language;
    char *languageName;
    pack_t *pack;
    searchpath_t *searchpath;

    FS_BuildOSPath(base, game, "", osPath);
    osPath[strlen(osPath) - 1] = '\0';
    pakFiles = Sys_ListFiles(osPath, ".pk3", NULL, &numPakFiles, 0);

    if (numPakFiles > FS_MAX_PAKFILES) {
        /* ORIGINAL_BINARY_BUG: stock's two numeric conversions are the
         * incomplete spellings %1/%1; see
         * original-bugs/coduomp-pak-limit-warning-malformed-format.md. */
        Com_Printf("WARNING: Exceeded max number of pak files in %s/%s "
                   "(%1/%1)\n",
                   base, game, numPakFiles, FS_MAX_PAKFILES);
        numPakFiles = FS_MAX_PAKFILES;
    }

    for (index = 0; index < numPakFiles; index++) {
        sortedPakFiles[index] = pakFiles[index];
        if (Q_strncmp(sortedPakFiles[index], "localized_",
                         FS_LOCALIZED_PREFIX_LENGTH) == 0) {
            memcpy(sortedPakFiles[index], "          ",
                   FS_LOCALIZED_PREFIX_LENGTH);
        }
    }

    qsort(sortedPakFiles, (size_t)numPakFiles, sizeof(*sortedPakFiles),
          paksort);

    for (index = 0; index < numPakFiles; index++) {
        if (Q_strncmp(sortedPakFiles[index], "          ",
                         FS_LOCALIZED_PREFIX_LENGTH) == 0) {
            memcpy(sortedPakFiles[index], "localized_",
                   FS_LOCALIZED_PREFIX_LENGTH);
            localized = 1;
            languageName = PakFileLanguage(sortedPakFiles[index]);
            if (*languageName == '\0') {
                Com_Printf("WARNING: Localized assets pak file %s/%s/%s has "
                           "invalid name (no language specified). Proper "
                           "naming convention is: "
                           "localized_[language]_pak#.pk3\n",
                           base, game, sortedPakFiles[index]);
                continue;
            }
            if (Q_stricmp(languageName, "english") != 0) {
                continue;
            }
        } else {
            localized = 0;
        }

        language = 0;
        FS_BuildOSPath(base, game, sortedPakFiles[index], osPath);
        pack = FS_LoadZipFile(osPath, sortedPakFiles[index]);
        if (pack == NULL) {
            continue;
        }

        strcpy(pack->pakGamename, game);
        searchpath = Z_Malloc((size_t)sizeof(*searchpath));
        searchpath->pack = pack;
        searchpath->localized = localized;
        searchpath->language = language;
        FS_AddSearchPath(searchpath);
    }

    Sys_FreeFileList(pakFiles);
}
