#include "rumble.h"

#include <stdio.h>

#include "decomp/global_state.h"

SM64RumbleCallbackFunctionPtr g_rumble_callback_func = NULL;

static int16_t gShimWindow = 0;
static int16_t gShimPulseRate = 7;
static int16_t gShimFrameCounter = 0;
static int16_t gShimLevel = 80;

extern void queue_rumble_data_for_mario(int32_t marioId, int16_t level, int16_t time)
{
    if (g_rumble_callback_func)
        g_rumble_callback_func(marioId, level, time);
}

extern void queue_rumble_data(int16_t level, int16_t time)
{
    int32_t marioId = -1;

    if (g_state)
        marioId = g_state->mgMarioId;

    queue_rumble_data_for_mario(marioId, level, time);
}

extern void reset_rumble_timers(void)
{
    if (gShimWindow <= 0)
        gShimWindow = 7;

    if (gShimWindow < 4)
        gShimWindow = 4;

    gShimPulseRate = 7;
}

extern void reset_rumble_timers_2(int32_t a0)
{
    if (gShimWindow <= 0)
        gShimWindow = 7;

    if (gShimWindow < 4)
        gShimWindow = 4;

    if (a0 == 4) gShimPulseRate = 1;
    if (a0 == 3) gShimPulseRate = 2;
    if (a0 == 2) gShimPulseRate = 3;
    if (a0 == 1) gShimPulseRate = 4;
    if (a0 == 0) gShimPulseRate = 5;
}

extern void rumble_shim_update(void)
{
    if (gShimWindow <= 0)
    {
        gShimFrameCounter = 0;
        return;
    }

    gShimWindow--;
    gShimFrameCounter++;

    if (gShimPulseRate <= 0)
        return;

    if ((gShimFrameCounter % gShimPulseRate) == 0)
    {
        queue_rumble_data(gShimLevel, 33 * 3);
    }
}