#include <stdint.h>

#include "fs_private.h"

int32_t FS_FOpenFileByMode(const char *qpath,
                                          int32_t *handle,
                                          coduo_fs_mode_t mode)
{
    int32_t result;
    qboolean sync;

    result = 6969;
    sync = 0;

    switch (mode) {
    case CODUO_FS_READ:
        result = FS_FOpenFileRead(qpath, handle, 1);
        break;
    case CODUO_FS_WRITE:
        /* ORIGINAL_BINARY_BUG: this store precedes the common null-handle
         * check; see
         * original-bugs/coduomp-fopenbymode-null-write-handle.md. */
        *handle = FS_FOpenFileWrite(qpath);
        result = 0;
        if (*handle == 0) {
            result = -1;
        }
        break;
    case CODUO_FS_APPEND_SYNC:
        sync = 1;
        /* fall through */
    case CODUO_FS_APPEND:
        /* ORIGINAL_BINARY_BUG: append repeats the same pre-check store; see
         * original-bugs/coduomp-fopenbymode-null-write-handle.md. */
        *handle = FS_FOpenFileAppend(qpath);
        result = 0;
        if (*handle == 0) {
            result = -1;
        }
        break;
    default:
        Com_Error(0, "\x15" "FSH_FOpenFile: bad mode");
        break;
    }

    if (handle == NULL) {
        return result;
    }

    if (*handle != 0) {
        if (fs_handleFiles[*handle].zipArchive == NULL) {
            fs_handleFiles[*handle].position =
                (long)ftell(
                    FS_LoadIOFile(fs_handleFiles[*handle].ioObject));
        } else {
            fs_handleFiles[*handle].position =
                Unzip_TellCurrentFile(FS_LoadZipIOFile(
                    fs_handleFiles[*handle].ioObject));
        }

        fs_handleFiles[*handle].size = result;
        fs_handleFiles[*handle].seekCallbackGuard = 0;
    }

    fs_handleFiles[*handle].sync = sync;

    return result;
}
