/*
 * DESCRIPTION:
 * Mouse functions.
*/

#include "mouse.h"

/* Updates the mouse. */
void
mouse_update(Mouse* self)
{
        s32 state;
	s32 x;
	s32 y;

        memcpy(&self->previous, &self->current, sizeof(bool) * MOUSE_BUTTON_COUNT);
        memset(&self->current, '\0', sizeof(bool) * MOUSE_BUTTON_COUNT);

        state = SDL_GetMouseState(NULL, NULL);

        if ((state & SDL_BUTTON_LMASK) != 0)
                self->current[MOUSE_BUTTON_LEFT] = true;

        if ((state & SDL_BUTTON_MMASK) != 0)
                self->current[MOUSE_BUTTON_MIDDLE] = true;

        if ((state & SDL_BUTTON_RMASK) != 0)
                self->current[MOUSE_BUTTON_RIGHT] = true;

        if ((state & SDL_BUTTON_X1) != 0)
                self->current[MOUSE_BUTTON_X1] = true;

        if ((state & SDL_BUTTON_X2) != 0)
                self->current[MOUSE_BUTTON_X2] = true;

	SDL_GetMouseState(&x, &y);

	self->position[0] = x;
	self->position[1] = y;
}

/* Is a given mouse button pressed? */
bool
mouse_press(Mouse* self, MouseButtonType type)
{
        return (self->current[type] && !self->previous[type]);
}

/* Is a given mouse button held? */
bool
mouse_held(Mouse* self, MouseButtonType type)
{
        return (self->current[type] && self->previous[type]);
}

/* Is a given mouse button released? */
bool
mouse_release(Mouse* self, MouseButtonType type)
{
        return (!self->current[type] && self->previous[type]);
}

/* Fetches the world position of the cursor. */
void
mouse_world_position_get(Mouse* self, Renderer* renderer, vec2 position)
{
	vec2 mousePosition;

	mousePosition[0] = (f32)self->position[0];
	mousePosition[1] = (f32)self->position[1];

	renderer_world_position_from_window_position(renderer, mousePosition, position);
}

/* Returns the angle of the cursor's world position and a world position specified. */
f32
mouse_angle_from_world_position_get(Mouse* self, Renderer* renderer, vec2 position)
{
	vec2 mousePosition;

	mouse_world_position_get(self, renderer, mousePosition);

	return (f32)ATAN(mousePosition[0], position[0], mousePosition[1], position[1]);
}
