#include <libusb-1.0/libusb.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

  // initiate the usb thing

  libusb_context *context;
  int statusInit = libusb_init(&context);
  if (statusInit != 0) {
    perror("libusb_init");
    exit(-1);
  }
  /* ... some code ... */

  // actually enumerates all the usb and gives some infos abot the usb things

  libusb_device **list;
  ssize_t count = libusb_get_device_list(context, &list);
  if (count < 0) {
    perror("libusb_get_device_list");
    exit(-1);
  }
  ssize_t i = 0;
  for (i = 0; i < count; i++) {
    libusb_device *device = list[i];
    struct libusb_device_descriptor desc;

    int status = libusb_get_device_descriptor(device, &desc);
    if (status != 0)
      continue;

    uint8_t bus = libusb_get_bus_number(device);
    uint8_t address = libusb_get_device_address(device);

    printf("Device Found @ (Bus:Address) %d:%d\n", bus, address);
    printf("Vendor ID 0x0%x\n", desc.idVendor);
    printf("Product ID 0x0%x\n", desc.idProduct);

    // Ouverture du périphérique
    libusb_device_handle *handle;
    int statusDevice = libusb_open(device, &handle);
    if (statusDevice != 0) {
      perror("libusb_open");
      exit(-1);
    }
    /*
        // Si le méchant noyau est passé avant vous :
        int interface = 0; // TEST : FONCTIONNE MAIS CORRESPOND A QUOI?
        if (libusb_kernel_driver_active(handle, interface)) {
          int statusKDriver = libusb_detach_kernel_driver(handle, interface);
          if (statusKDriver != 0) {
            perror("libusb_detach_kernel_driver");
            exit(-1);
          }
        }

        // lectures des configs?
        int configuration = 0; // valueof("bConfigurationValue");
        int statusConfig = libusb_set_configuration(handle, configuration);
        if (statusConfig != 0) {
          perror("libusb_set_configuration"); /*exit(-1);*/
    /*   }
     */
    int MAXLEN_DESCRIPTOR_STRING = 200;
    uint8_t desc_idx = 2;
    uint16_t langid = 16;
    unsigned char data[200];

    // TEST 16
    for (desc_idx = 0; desc_idx < 16; desc_idx++) {
      int statusAscii = libusb_get_string_descriptor_ascii(
          handle, desc_idx, data, MAXLEN_DESCRIPTOR_STRING);
      if (statusAscii == -9) // TEST seems to be LIBUSB_ERROR
        break;
      printf("Descriptor string : %s ; %i\n", data, statusAscii);
    }
    /* ... some ... code */
    libusb_close(handle);
  }

  libusb_free_device_list(list, 1);

  libusb_exit(context);
  return 0;
}
