#include "fs_private.h"

#include "../core_command/cmd_private.h"

#define FS_DIR_MIN_ARGC 2
#define FS_DIR_MAX_ARGC 3
#define FS_DIR_PATH_ARG 1
#define FS_DIR_EXTENSION_ARG 2
#define FS_FDIR_FILTER_ARG 1
#define FS_TOUCH_FILE_ARG 1

void FS_Dir_f(void)
{
    const char *path;
    const char *extension;
    char **files;
    int numFiles;
    int index;

    if (Cmd_Argc() < FS_DIR_MIN_ARGC || Cmd_Argc() > FS_DIR_MAX_ARGC) {
        Com_Printf("usage: dir <directory> [extension]\n");
        return;
    }

    path = Cmd_Argv(FS_DIR_PATH_ARG);
    if (Cmd_Argc() == FS_DIR_MIN_ARGC) {
        extension = "";
    } else {
        extension = Cmd_Argv(FS_DIR_EXTENSION_ARG);
    }

    Com_Printf("Directory of %s %s\n", path, extension);
    Com_Printf("---------------\n");

    files = FS_ListFiles(path, extension, &numFiles);
    for (index = 0; index < numFiles; ++index) {
        Com_Printf("%s\n", files[index]);
    }
    FS_FreeFileList(files);
}

void FS_FDir_f(void)
{
    const char *filter;
    char **files;
    int numFiles;
    int index;

    if (Cmd_Argc() < FS_DIR_MIN_ARGC) {
        Com_Printf("usage: fdir <filter>\n");
        Com_Printf("example: fdir *q3dm*.bsp\n");
        return;
    }

    filter = Cmd_Argv(FS_FDIR_FILTER_ARG);
    Com_Printf("---------------\n");

    files = FS_ListFilteredFiles("", "", filter, &numFiles);
    FS_SortFileList(files, numFiles);
    for (index = 0; index < numFiles; ++index) {
        FS_ReplaceSeparators(files[index]);
        Com_Printf("%s\n", files[index]);
    }

    Com_Printf("%d files listed\n", numFiles);
    FS_FreeFileList(files);
}

void FS_TouchFile_f(void)
{
    if (Cmd_Argc() == FS_DIR_MIN_ARGC) {
        FS_TouchFile(Cmd_Argv(FS_TOUCH_FILE_ARG));
    } else {
        Com_Printf("Usage: touchFile <file>\n");
    }
}

void FS_AddCommands(void)
{
    Cmd_AddCommand("path", FS_Path_f);
    Cmd_AddCommand("fullpath", FS_FullPath_f);
    Cmd_AddCommand("dir", FS_Dir_f);
    Cmd_AddCommand("fdir", FS_FDir_f);
    Cmd_AddCommand("touchFile", FS_TouchFile_f);
}
