#pragma once

#include "l4rio.h"

//########################################################################
//############################### PadRIO #################################
//########################################################################
//
// A cockpit-less RIO: synthesizes the RIOBase control surface from an
// XInput controller and the PC keyboard, following vRIO's default
// binding profile. Selected with L4CONTROLS=PAD.
//
//   Left stick        -> joystick X/Y            [-1..1]
//   Left/right trigger-> left/right pedal        [0..1]
//   Right stick Y     -> throttle rate (position holds)  [0..1]
//   A / B             -> joystick trigger / reverse thrust
//   X / Y / LB / RB   -> pinky / thumb-low / thumb-low / thumb-high
//   DPad              -> joystick hat
//   Back / Start      -> config buttons (AuxUpperRight2 / 1)
//
//   Keyboard: WASD = stick deflect (spring-back), PgUp/PgDn = throttle,
//   Q/E = pedals, Space = trigger, R = reverse, arrows = hat, F1/F2 =
//   config buttons.
//
// Set L4PADFLIP to a string containing 'X' and/or 'Y' to invert the
// stick axes.
//
class PadRIO :
	public RIOBase
{
public:
	PadRIO();
	~PadRIO();

	Logical
		TestInstance() const;

	Logical
		GetNextEvent(RIOEvent *destinationPointer);

	void
		RequestAnalogUpdate();

	void
		GeneralReset();
	void
		ResetThrottle();

	void
		SetLamp(int lampNumber, int state);

	// Lamp state the game has commanded, indexed by RIO lamp number.
	// The on-screen cockpit buttons read this to light themselves.
	enum { lampCount = 64 };
	unsigned char
		lampState[lampCount];

	//---------------------------------------------------------------
	// On-screen cockpit buttons (MFDSplitView strips) press RIO units
	// through these; they are no-ops when no PadRIO is active (e.g.
	// real serial hardware selected).
	//---------------------------------------------------------------
	static void
		SetScreenButton(int unit, Logical pressed);
	static int
		GetLampState(int unit);
	static Logical
		IsActive()
			{ return activeInstance != NULL; }

protected:
	void
		PollInputs();
	void
		QueueEvent(const RIOEvent &an_event);

	enum { queueSize = 64 };
	enum { buttonUnits = 0x48 };	// through LastMappableButton

	RIOEvent
		eventQueue[queueSize];
	int
		queueHead, queueTail;

	static PadRIO
		*activeInstance;

	// pressed state driven by the on-screen cockpit buttons
	unsigned char
		screenButton[0x48];

	unsigned long
		lastPollTick,
		lastPadCheckTick;
	int
		padIndex;			// connected XInput slot, -1 = none
	Logical
		padReported;		// one-time connect/disconnect log flags
	Logical
		analogRequested;

	unsigned char
		buttonDown[buttonUnits];

	Scalar
		throttleAccum;
	Logical
		invertX, invertY;

	Scalar
		sentThrottle, sentLeftPedal, sentRightPedal,
		sentJoystickX, sentJoystickY;
};
