#include <pad.h>
#include <pad_private.h>
#include <pad/port.h>
#include <stddef.h>
#include <string.h>

static const char *const pads[] =
{
    "Pad 1",
    "Pad 2"
};

void pad_init(const int id, struct pad *const p)
{
    *p = (const struct pad)
    {
        .id = id
    };
}

void pad_port_update(struct pad *const p)
{
    static const int psx_keys[] =
    {
        [PAD_KEY_LEFT] = PAD_LEFT,
        [PAD_KEY_RIGHT] = PAD_RIGHT,
        [PAD_KEY_UP] = PAD_UP,
        [PAD_KEY_DOWN] = PAD_DOWN,
        [PAD_KEY_A] = PAD_CROSS,
        [PAD_KEY_B] = PAD_CIRCLE,
        [PAD_KEY_C] = PAD_TRIANGLE,
        [PAD_KEY_D] = PAD_SQUARE,
        [PAD_KEY_E] = PAD_L1,
        [PAD_KEY_OPTIONS] = PAD_START
    };

    p->mask = 0;
    PSX_PollPad(p->id, &p->port.pps);

    for (size_t i = 0; i < sizeof psx_keys / sizeof *psx_keys; i++)
    {
        const int mask = 1 << i;

        if (p->port.pps.buttons & psx_keys[i])
            p->mask |= mask;
        else
            p->mask &= ~mask;
    }
}

size_t pad_count(void)
{
    return sizeof pads / sizeof *pads;
}

const char *pad_name(const int id)
{
    return pads[id];
}
