#pragma once

#include "asset_io.hpp"
#include <RmlUi/Core/FileInterface.h>
#include <SDL3/SDL.h>

class SDLFileInterface : public Rml::FileInterface {
public:
    Rml::FileHandle Open(const Rml::String &path) override {
        SDL_IOStream *io = OpenAssetFile(path);
        return reinterpret_cast<Rml::FileHandle>(io);
    }

    void Close(Rml::FileHandle file) override {
        SDL_CloseIO(reinterpret_cast<SDL_IOStream *>(file));
    }

    size_t Read(void *buffer, size_t size, Rml::FileHandle file) override {
        return SDL_ReadIO(reinterpret_cast<SDL_IOStream *>(file), buffer, size);
    }

    bool Seek(Rml::FileHandle file, long offset, int origin) override {
        SDL_IOWhence whence = SDL_IO_SEEK_SET;
        if (origin == SEEK_CUR) whence = SDL_IO_SEEK_CUR;
        else if (origin == SEEK_END) whence = SDL_IO_SEEK_END;

        return SDL_SeekIO(reinterpret_cast<SDL_IOStream *>(file), offset, whence) >= 0;
    }

    size_t Tell(Rml::FileHandle file) override {
        return static_cast<size_t>(SDL_TellIO(reinterpret_cast<SDL_IOStream *>(file)));
    }

    size_t Length(Rml::FileHandle file) override {
        return static_cast<size_t>(SDL_GetIOSize(reinterpret_cast<SDL_IOStream *>(file)));
    }
};