#include "USBGamepad.h"
#include <string.h>

USBGamepad_ Gamepad;

USBGamepad_::USBGamepad_(void) {
  _report.axisX = 0;
  _report.axisY = 0;
  _report.axisZ = 0;
  _report.axisRz = 0;
  _report.triggerL = 0;
  _report.triggerR = 0;
  _report.buttons = 0;
  _report.hatSwitch = DPAD_CENTERED;
}

void USBGamepad_::begin(void) {
    _report.axisX = 0;
    _report.axisY = 0;
    _report.axisZ = 0;
    _report.axisRz = 0;
    _report.triggerL = 0;
    _report.triggerR = 0;
    _report.buttons = 0;
    _report.hatSwitch = DPAD_CENTERED;
    USB_init();
}

void USBGamepad_::end(void) {
}

void USBGamepad_::sendReport() {
  USB_write((uint8_t*)&_report, sizeof(GamepadReport));
}

void USBGamepad_::setLeftStick(int8_t x, int8_t y) {
  _report.axisX = x;
  _report.axisY = y;
}

void USBGamepad_::setRightStick(int8_t x, int8_t y) {
  _report.axisZ = x;
  _report.axisRz = y;
}

void USBGamepad_::setTriggers(uint8_t left, uint8_t right) {
  _report.triggerL = left;
  _report.triggerR = right;
}

void USBGamepad_::press(uint8_t button) {
  if (button > 15) return;
  _report.buttons |= (1 << button);
}

void USBGamepad_::release(uint8_t button) {
  if (button > 15) return;
  _report.buttons &= ~(1 << button);
}

void USBGamepad_::releaseAll() {
  _report.buttons = 0;
}

bool USBGamepad_::isPressed(uint8_t button) {
  if (button > 15) return false;
  return (_report.buttons & (1 << button));
}

void USBGamepad_::setHat(uint8_t direction) {
  if (direction > 8) direction = 8;
  _report.hatSwitch = direction;
}
