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

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

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

#include "corsair_strafe2.h"

static absolute_time_t lastRead;


extern void core1_main();

int main(void) {
	// default 125MHz is not appropreate. Sysclock should be multiple of 12MHz.
	set_sys_clock_khz(144000, true);

	// initialize the ADC for reading the attached LDR
	startADC();

	sleep_ms(10);

	// run TinyUSB host process on core 1
	multicore_reset_core1();
	multicore_launch_core1(core1_main);

	// run TinyUSB device process on core 0
	tud_init(0);

	while (true) {
		// read the ADC every 500ms
		if ( absolute_time_diff_us(lastRead, get_absolute_time()) > 500000) {
			get_light();
		}
		// run TinyUSB device task
	    tud_task(); 
	}

	return 0;
}


// Invoked when received SET_REPORT control request or
// received data on OUT endpoint ( Report ID = 0, Type = 0 )

void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize)
{
	
	if (instance == 0 && report_type==HID_REPORT_TYPE_OUTPUT &&                 report_id==REPORT_ID_KEYBOARD) {
		// received keyboard indicator LED status from host, so update on
		// the keyboard
		set_indicator(buffer,bufsize);
	}

    // echo the HID report to CDC for debugging
    char tempbuf[128];
    size_t count;
    if(bufsize>0) {
        count = sprintf(tempbuf, "\nReceived device set report type %u on interface %u with ID %u (%u)\n", report_type, instance, report_id, bufsize);
        tud_cdc_write(tempbuf, count);
        for(int i=0;i<bufsize;i++){
            count=sprintf(tempbuf,"%02X ",buffer[i]);
            tud_cdc_write(tempbuf,count);
        }
        count = sprintf(tempbuf, "\n");
        tud_cdc_write(tempbuf,count);
        tud_cdc_write_flush();
    }
}

// Invoked when received GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request

uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen)
{
	// TODO not Implemented
	(void) instance;
	(void) report_id;
	(void) report_type;
	(void) buffer;
	(void) reqlen;

	return 0;
}
