#include "sys_interaction.h"
#include "system.h"
#include "sys_vr.h"
#include "sys_vr_passthru.h"
#include "sys_undo.h"

static uint32_t tracked_id = 0xfffffffful;
static unsigned toolidx = 0;
static int touchdown = 0;
static yrTexture tpadbut_undo = NULL;
static yrTexture tpadbut_undo_glow = NULL;

static void undo_shutdown(void);
static void undo_settrackedid(uint32_t, unsigned);
static void undo_tick(void);
static int  undo_canfreeze(void);
static void undo_forceidle(void);
static int	undo_getpokepos(vec4f* pos, vec4f* dir, float* len) {return 0;}

int tool_undo_init(func_tool_shutdown* st_sd,
				   func_tool_settrackedid* ft_sti,
				   func_tool_tick* ft_t,
				   func_tool_canfreeze* ft_cf,
				   func_tool_forceidle* ft_fi,
				   func_tool_getpokepos* ft_gpp,
				   func_tool_renderwindow* ft_rw,
				   func_tool_poke* ft_p)
{
	*st_sd	= undo_shutdown;
	*ft_sti	= undo_settrackedid;
	*ft_t	= undo_tick;
	*ft_cf	= undo_canfreeze;
	*ft_fi	= undo_forceidle;
	*ft_gpp = undo_getpokepos;
	*ft_rw	= nullfunc;
	*ft_p	= nullfunc;

	tracked_id = 0xfffffffful;
	toolidx = 0;
	touchdown = 0;
	tpadbut_undo		= yrTexture_loadfile("data/vr/tpadbut_undo.png");		if(!tpadbut_undo) return -1;
	tpadbut_undo_glow	= yrTexture_loadfile("data/vr/tpadbut_undo_glow.png");	if(!tpadbut_undo_glow) return -1;

	return 0;
}

static void undo_shutdown(void)
{
	yrTexture_unload(tpadbut_undo);
	yrTexture_unload(tpadbut_undo_glow);
	tpadbut_undo = NULL;
	tpadbut_undo_glow = NULL;
}

static void undo_settrackedid(uint32_t tr_id, unsigned tool_idx)
{
	tracked_id = tr_id;
	toolidx = tool_idx;
}

static void undo_tick(void)
{
	VRControllerState_t cbuttons = {0};
	ovrSystem_GetControllerState(tracked_id, &cbuttons);
	float touchx = cbuttons.rAxis[EVRButtonId_k_EButton_SteamVR_Touchpad - EVRButtonId_k_EButton_Axis0].x;
	float touchy = cbuttons.rAxis[EVRButtonId_k_EButton_SteamVR_Touchpad - EVRButtonId_k_EButton_Axis0].y;
	int touchd = 0!=(cbuttons.ulButtonPressed & (1ull << EVRButtonId_k_EButton_SteamVR_Touchpad));

	//draw buttons
	yrRenderTrackedOverlay_clear(toolidx);
	if(touchd || touchx != 0.0f || touchy != 0.0f) {
		yrRenderTrackedOverlay_draw(toolidx, tpadbut_undo_glow, copysignf(1.0, touchx), -1.0f, 0.0f, 1.0f, touchd ? 0xFFFF8010 : 0x80FF8010);
	}
	yrRenderTrackedOverlay_draw(toolidx, tpadbut_undo, -1.0f, -1.0f, 0.0f, 1.0f, 0xFFFFFFFF);
	yrRenderTrackedOverlay_draw(toolidx, tpadbut_undo, 1.0f, -1.0f, 0.0f, 1.0f, 0xFFFFFFFF);
	yrRenderTrackedOverlay_render(toolidx);

	if(!touchdown && touchd) {
		if(touchx < 0.0f) {
			yrUndo_undo();
		} else {
			yrUndo_redo();
		}
	}

	touchdown = touchd;
}

static int undo_canfreeze(void)
{
	return 1;
}

static void	undo_forceidle(void)
{
	;//nothing
}
