#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "pico/bootrom.h"

#include "pio_usb.h"
#include "tusb.h"
#include "usb_descriptors.h"
#include "corsair_strafe2.h"

static bool enabled = false;
static uint8_t kb_addr = 0;
static uint8_t kb_inst = 0;

static uint8_t const* last_report;
static uint16_t last_len;
static bool resend = false;

static unsigned char nkro_buf[NKRO_BUF_SIZE];
static uint8_t forward_id=0;

void forward_report(uint8_t const* report, uint16_t len);

// main process for core 1 to handle USB host events
void core1_main() {
	sleep_ms(10);

	// configure PIO USB for use as TinyUSB host
	pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG;
	pio_cfg.alarm_pool = (void*) alarm_pool_create(2,1);
	tuh_configure(1, TUH_CFGID_RPI_PIO_USB_CONFIGURATION, &pio_cfg);
	tuh_init(1);

	while (true) {
	if (enabled) {
		// resend last HID report if it was not successful
		if (resend) {
			forward_report(last_report,last_len);
		} else {
			// check light and set keyboard color
			rgb_task(kb_addr, 1, 0);
		}
	}
		tuh_task(); // tinyusb host task
	}
}

// Invoked when device with hid interface is mounted
void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len)
{
	(void)desc_report;
	(void)desc_len;

	uint16_t vid, pid;
	tuh_vid_pid_get(dev_addr, &vid, &pid);
	const char* protocol_str[] = { "None", "Keyboard", "Mouse" };
	uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance);

	// send device vid:pid information to CDC for debugging
	char tempbuf[256];
	size_t count = sprintf(tempbuf, "[%04x:%04x][%u] HID Interface %u, Protocol = %s \n", vid, pid, dev_addr, instance, protocol_str[itf_protocol]);
	tud_cdc_write(tempbuf, count);
	tud_cdc_write_flush();

	// request to receive report if mounted device matches Strafe Mk. 2
	if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD && vid==CORSAIR_KEYBOARD_VID && pid==CORSAIR_STRAFE2_PID)
	{
		enabled = true;
		kb_addr = dev_addr;
		kb_inst = instance;
		if ( !tuh_hid_receive_report(dev_addr, instance) )
		{
			tud_cdc_write_str("Error: cannot request report\r\n");
		}
	}

}

// Invoked when device with hid interface is un-mounted
void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance)
{
	if(dev_addr==kb_addr && instance==kb_inst){
		kb_addr=0;
		kb_inst=0;
		enabled=false;
	}
}

// Invoked when received report from device via interrupt endpoint
void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len)
{
	char tempbuf[64];
	if(len>0) {
		// echo  HID report to CDC for debugging
		size_t count = sprintf(tempbuf, "\n[%u] Forward message on interface %u (%u)\n", dev_addr, instance, len);
		tud_cdc_write(tempbuf, count);
	}

	// passthrough report to TinyUSB device
	if (enabled && kb_addr == dev_addr && kb_inst == instance) {
		for(int i=0;i<len;i++){
			size_t count=sprintf(tempbuf,"%02X ",report[i]);
			tud_cdc_write(tempbuf,count);
		}

		forward_report(report, len);
	}
	tud_cdc_write_flush();

	// continue to request to receive report
	if ( !tuh_hid_receive_report(dev_addr, instance) )
	{
		//tud_cdc_write_str("Error: cannot request report\r\n");
	}
}


void forward_report(uint8_t const* report, uint16_t len) {
	char tempbuf[64];
	bool result = false;

	// check if report ID matches is for keyboard and send updated NKRO
	// key bitmap if it is, and otherwise send to Consumer Control
	// device for media keys
	forward_id = corsair2nkro(&report[1], nkro_buf, len-1);
	if ( forward_id == REPORT_ID_KEYBOARD) {
		result = tud_hid_report(REPORT_ID_KEYBOARD, nkro_buf, NKRO_BUF_SIZE);
	}
	if ( forward_id == REPORT_ID_CONSUMER_CONTROL) {
		result = tud_hid_report(REPORT_ID_CONSUMER_CONTROL, nkro_buf, 4);
	}

	if ( result ) {
		// message was sent
		resend = false;
	} else {
		// message did not send properly, so resent on next cycle
		last_report = report;
		last_len = len;
		resend = true;
	}
}

void set_indicator(uint8_t const* buffer, uint16_t len) {
    // received new keyboard indicator LED status from host - pass to
    // keyboard device so indicators can be updated
    tuh_hid_set_report(kb_addr, kb_inst, REPORT_ID_KEYBOARD, HID_REPORT_TYPE_OUTPUT, buffer, len);
}
