#include "cmsis_os2.h" // CMSIS RTOS header file

#include "rl_fs.h"  // Keil.MDK-Pro::File System:CORE
#include "rl_usb.h" // Keil.MDK-Pro::USB:CORE

#include "USBH_MSC.h"

#include "kmdw_console.h"
#include "kmdw_memory.h"

/*----------------------------------------------------------------------------
 *      Thread for usb host examples
 *---------------------------------------------------------------------------*/



osThreadId_t tid_Thread; // thread id

void usbh_cmsis_user_thread(void *argument); // thread function

void usbh_cmsis_example_init(void)
{
  osThreadNew(usbh_cmsis_user_thread, NULL, NULL);
}

void usbh_cmsis_user_thread(void *argument)
{
  usbStatus usb_status; // USB status
  int32_t msc_status;   // MSC status
  FILE *f;              // Pointer to stream object
  uint8_t con = 0U;     // Connection status of MSC(s)

  uint8_t *bfptr = (uint8_t *)kmdw_ddr_reserve(4*1024*1024);

  // init USB host through MDK middleware
  USBH_Initialize(0U);
  if (usb_status != usbOK)
  {
    for (;;)
    {
    } // Handle USB Host 0 init failure
  }
  
  for (;;)
  {
    msc_status = USBH_MSC_DriveGetMediaStatus("U0:"); // Get MSC device status
    if (msc_status == USBH_MSC_OK)
    {
      if (con == 0U)
      {           // If stick was not connected previously
        con = 1U; // Stick got connected
        msc_status = USBH_MSC_DriveMount("U0:");
        if (msc_status != USBH_MSC_OK)
        {
          continue; // Handle U0: mount failure
        }
        f = fopen("test.txt", "wb"); // Open/create file for writing
        if (f == NULL)
        {
          continue; // Handle file opening/creation failure
        }

        size_t wsize = fwrite(bfptr, 1, 4*1024*1024, f);

        fclose(f); // Close file

        kmdw_printf("Write file done, wsize %u\n", wsize);

        msc_status = USBH_MSC_DriveUnmount("U0:");
        if (msc_status != USBH_MSC_OK)
        {
          continue; // Handle U0: dismount failure
        }
      }
    }
    else
    {
      if (con == 1U)
      {           // If stick was connected previously
        con = 0U; // Stick got disconnected
      }
    }
    osDelay(100U);
  }
}
