#include <pad.h>
#include <SDL.h>
#include <SDL_joystick.h>
#include <stdio.h>

static void global_init(void)
{
    SDL_JoystickEventState(SDL_ENABLE);
}

void pad_port_update(struct pad *const p)
{
    enum {FLAGS = SDL_JOYBUTTONDOWNMASK
        | SDL_JOYBUTTONUPMASK
        | SDL_JOYAXISMOTIONMASK
        | SDL_QUITMASK};

    SDL_Event ev;
    int n;

    while ((n = SDL_PeepEvents(&ev, 1, SDL_GETEVENT, FLAGS)) > 0)
    {
    }

    if (n < 0)
        fprintf(stderr, "%s: SDL_PeepEvents: %s\n", __func__, SDL_GetError());
}

void pad_init(const int id, struct pad *const p)
{
    static bool init;

    if (!init)
    {
        global_init();
        init = true;
    }

    if (!(p->port.joystick = SDL_JoystickOpen(id)))
        fprintf(stderr, "%s: SDL_JoystickOpen failed: %s\n",
            __func__, SDL_GetError());
    else
        printf("%s: num axis: %d\n", __func__,
            SDL_JoystickNumAxes(p->port.joystick));
}

size_t pad_count(void)
{
    const int res = SDL_NumJoysticks();

    return res > 0 ? res : 0;
}

const char *pad_name(const int id)
{
    return SDL_JoystickName(id);
}
