/*
Nintendo Switch Fightstick - Proof-of-Concept

Based on the LUFA library's Low-Level Joystick Demo
	(C) Dean Camera
Based on the HORI's Pokken Tournament Pro Pad design
	(C) HORI

This project implements a modified version of HORI's Pokken Tournament Pro Pad
USB descriptors to allow for the creation of custom controllers for the
Nintendo Switch. This also works to a limited degree on the PS3.

Since System Update v3.0.0, the Nintendo Switch recognizes the Pokken
Tournament Pro Pad as a Pro Controller. Physical design limitations prevent
the Pokken Controller from functioning at the same level as the Pro
Controller. However, by default most of the descriptors are there, with the
exception of Home and Capture. Descriptor modification allows us to unlock
these buttons for our use.
*/

#include "Joystick.h"

// Main entry point.
int main(void) {
	// We'll start by performing hardware and peripheral setup.

	DDRD = 0b01000000;
	PORTD = 0b10111111;

	DDRE = 0b11111100;
	PORTE = 0b00000011;

	DDRC = 0b11111100;
	PORTC = 0b00000011;

	DDRB = 0b11000000;
	PORTB = 0b00111111;


	SetupHardware();
	// We'll then enable global interrupts for our use.
	GlobalInterruptEnable();
	// Once that's done, we'll enter an infinite loop.
	for (;;)
	{
		// We need to run our task to process and deliver data for our IN and OUT endpoints.
		HID_Task();
		// We also need to run the main USB management task.
		USB_USBTask();
	}
}

// Configures hardware and peripherals, such as the USB peripherals.
void SetupHardware(void) {
	// We need to disable watchdog if enabled by bootloader/fuses.
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	// We need to disable clock division before initializing the USB hardware.
	clock_prescale_set(clock_div_1);
	// We can then initialize our hardware and peripherals, including the USB stack.
	
	// The USB stack should be initialized last.
	USB_Init();
}

// Fired to indicate that the device is enumerating.
void EVENT_USB_Device_Connect(void) {
	// We can indicate that we're enumerating here (via status LEDs, sound, etc.).
}

// Fired to indicate that the device is no longer connected to a host.
void EVENT_USB_Device_Disconnect(void) {
	// We can indicate that our device is not ready (via status LEDs, sound, etc.).
}

// Fired when the host set the current configuration of the USB device after enumeration.
void EVENT_USB_Device_ConfigurationChanged(void) {
	bool ConfigSuccess = true;

	// We setup the HID report endpoints.
	ConfigSuccess &= Endpoint_ConfigureEndpoint(JOYSTICK_OUT_EPADDR, EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);
	ConfigSuccess &= Endpoint_ConfigureEndpoint(JOYSTICK_IN_EPADDR, EP_TYPE_INTERRUPT, JOYSTICK_EPSIZE, 1);

	// We can read ConfigSuccess to indicate a success or failure at this point.
}

// Process control requests sent to the device from the USB host.
void EVENT_USB_Device_ControlRequest(void) {
	// We can handle two control requests: a GetReport and a SetReport.

	// Not used here, it looks like we don't receive control request from the Switch.
}

// Process and deliver data from IN and OUT endpoints.
void HID_Task(void) {
	// If the device isn't connected and properly configured, we can't do anything here.
	if (USB_DeviceState != DEVICE_STATE_Configured)
		return;

	// We'll start with the OUT endpoint.
	Endpoint_SelectEndpoint(JOYSTICK_OUT_EPADDR);
	// We'll check to see if we received something on the OUT endpoint.
	if (Endpoint_IsOUTReceived())
	{
		// If we did, and the packet has data, we'll react to it.
		if (Endpoint_IsReadWriteAllowed())
		{
			// We'll create a place to store our data received from the host.
			USB_JoystickReport_Output_t JoystickOutputData;
			// We'll then take in that data, setting it up in our storage.
			while(Endpoint_Read_Stream_LE(&JoystickOutputData, sizeof(JoystickOutputData), NULL) != ENDPOINT_RWSTREAM_NoError);
			// At this point, we can react to this data.

			// However, since we're not doing anything with this data, we abandon it.
		}
		// Regardless of whether we reacted to the data, we acknowledge an OUT packet on this endpoint.
		Endpoint_ClearOUT();
	}

	// We'll then move on to the IN endpoint.
	Endpoint_SelectEndpoint(JOYSTICK_IN_EPADDR);
	// We first check to see if the host is ready to accept data.
	if (Endpoint_IsINReady())
	{
		// We'll create an empty report.
		USB_JoystickReport_Input_t JoystickInputData;
		// We'll then populate this report with what we want to send to the host.
		GetNextReport(&JoystickInputData);
		// Once populated, we can output this data to the host. We do this by first writing the data to the control stream.
		while(Endpoint_Write_Stream_LE(&JoystickInputData, sizeof(JoystickInputData), NULL) != ENDPOINT_RWSTREAM_NoError);
		// We then send an IN packet on this endpoint.
		Endpoint_ClearIN();
	}
}

#define ECHOES 2
int echoes = 0;
USB_JoystickReport_Input_t last_report;

int report_count = 0;
int xpos = 0;
int ypos = 0;
int bufindex = 0;
int duration_count = 0;
int portsval = 0;

// Prepare the next report for the host.
void GetNextReport(USB_JoystickReport_Input_t* const ReportData) {

	// Prepare an empty report
	memset(ReportData, 0, sizeof(USB_JoystickReport_Input_t));
	ReportData->LX = STICK_CENTER;
	ReportData->LY = STICK_CENTER;
	ReportData->RX = STICK_CENTER;
	ReportData->RY = STICK_CENTER;
	ReportData->HAT = HAT_CENTER;

	// Repeat ECHOES times the last report
	if (echoes > 0)
	{
		memcpy(ReportData, &last_report, sizeof(USB_JoystickReport_Input_t));
		echoes--;
		return;
	}

	int value;
	// States and moves management

	int hat_up = !(PIND & _BV(PIND1));
	int hat_right = !(PIND & _BV(PIND5));
	int hat_down = !(PIND & _BV(PIND4));
	int hat_left = !(PIND & _BV(PIND3));

	int minus = !(PIND & _BV(PIND2));
	int plus = !(PINB & _BV(PINB4));

	int bumper = !(PIND & _BV(PIND7));

	int rs_up = !(PINC & _BV(PINC1));
	int rs_down = !(PINC & _BV(PINC0));
	int rs_left = !(PINE & _BV(PINE1));
	int rs_right = !(PINE & _BV(PINE0));

	int capture = !(PIND & _BV(PIND0));
	int home = !(PINB & _BV(PINB0));

	int button_y = !(PINB & _BV(PINB5));
	int button_x = !(PINB & _BV(PINB1));
	int button_a = !(PINB & _BV(PINB3));
	int button_b = !(PINB & _BV(PINB2));


	if (plus)
		ReportData->Button |= SWITCH_PLUS;
	if (minus)
		ReportData->Button |= SWITCH_MINUS;
	
	if (capture)
		ReportData->Button |= SWITCH_CAPTURE;
	if (home)
		ReportData->Button |= SWITCH_HOME;
	
	if (button_a)
		ReportData->Button |= SWITCH_A;
	if (button_b)
		ReportData->Button |= SWITCH_B;
	if (button_x)
		ReportData->Button |= SWITCH_X;
	if (button_y)
		ReportData->Button |= SWITCH_Y;
	
	if (bumper)
		ReportData->Button |= SWITCH_L;
	
	if (rs_up)
		ReportData->RY = 0;
	else if (rs_down)
		ReportData->RY = 255;
	else if (rs_left)
		ReportData->RX = 0;
	else if (rs_right)
		ReportData->RX = 255;
	
	if (hat_up)
	{
		if (hat_right)
			ReportData->HAT = HAT_TOP_RIGHT;
		else if (hat_left)
			ReportData->HAT = HAT_TOP_LEFT;
		else
			ReportData->HAT = HAT_TOP;
	}
	else if (hat_right)
	{
		if (hat_down)
			ReportData->HAT = HAT_BOTTOM_RIGHT;
		else
			ReportData->HAT = HAT_RIGHT;
	}
	else if (hat_down)
	{
		if (hat_left)
			ReportData->HAT = HAT_BOTTOM_LEFT;
		else
			ReportData->HAT = HAT_BOTTOM;
	}
	else if (hat_left)
	{
		ReportData->HAT = HAT_LEFT;
	}



	// Prepare to echo this report
	memcpy(&last_report, ReportData, sizeof(USB_JoystickReport_Input_t));
	echoes = ECHOES;

}
