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

#include "fs_private.h"

enum {
    FS_LOCALIZED_GAME_NAME_SIZE = 64,
};

void FS_AddGameDirectory(const char *base, const char *game, qboolean localized,
                  int32_t language)
{
    searchpath_t *search;
    searchpath_t *newSearch;
    directory_t *directory;
    const char *existingFolderType;
    char osPath[FS_OSPATH_SIZE];
    char gameName[FS_LOCALIZED_GAME_NAME_SIZE];

    if (localized == 0) {
        Q_strncpyz(gameName, game, sizeof(gameName));
    } else {
        Com_sprintf(gameName, sizeof(gameName), "%s_%s", game, "english");
    }

    for (search = FS_SearchpathHead(); search != NULL;
         search = FS_SearchpathNext(search)) {
        if (search->dir == NULL) {
            continue;
        }

        directory = search->dir;
        if (Q_stricmp(directory->path, base) != 0 ||
            Q_stricmp(directory->gamedir, gameName) != 0) {
            continue;
        }

        if (search->localized != localized) {
            if (search->localized == 0) {
                existingFolderType = "non-localized";
            } else {
                existingFolderType = "localized";
            }
            Com_Printf("WARNING: game folder %s/%s added as both localized & "
                       "non-localized. Using folder as %s\n",
                       base, gameName, existingFolderType);
        }

        if (search->localized == 0) {
            return;
        }
        if (search->language == language) {
            return;
        }

        /* ORIGINAL_BINARY_BUG: stock supplies neither string required by
         * this format; see
         * original-bugs/coduomp-game-directory-warning-missing-arguments.md. */
        Com_Printf("WARNING: game golder %s/%s re-added as localized folder "
                   "with different language\n");
        return;
    }

    if (localized == 0) {
        Q_strncpyz(fs_currentGameDir, gameName, sizeof(fs_currentGameDir));
    } else {
        FS_BuildOSPath(base, gameName, "", osPath);
        osPath[strlen(osPath) - 1] = '\0';
        if (FS_DirectoryHasNonDotEntries(osPath) == 0) {
            return;
        }
    }

    newSearch = Z_Malloc((size_t)sizeof(*newSearch));
    directory = Z_Malloc((size_t)sizeof(*directory));
    newSearch->dir = directory;
    Q_strncpyz(directory->path, base, sizeof(directory->path));
    Q_strncpyz(directory->gamedir, gameName, sizeof(directory->gamedir));
    newSearch->localized = localized;
    newSearch->language = language;
    FS_AddSearchPath(newSearch);
    FS_AddPakFilesForGameDirectory(base, gameName);
}
