use stm32f0xx_hal::usb::UsbBusType;

use usb_device::bus::UsbBusAllocator;
use usb_device::prelude::*;

use usbd_serial::SerialPort;

/// pid.codes VID
const VENDOR_ID: u16 = 0x1209;

/// pid.codes Test PID -- **do not use outside of testing!**  
/// *TODO: apply for unique PID once project is finished*
const PRODUCT_ID: u16 = 0x0006;

pub struct Usb<'a> {
    usb_dev: UsbDevice<'a, UsbBusType>,
    serial: SerialPort<'a, UsbBusType>,
}

impl<'a> Usb<'a> {
    pub fn new(usb_bus: &'a UsbBusAllocator<UsbBusType>) -> Self {
        let serial = SerialPort::new(usb_bus);

        let usb_dev = UsbDeviceBuilder::new(usb_bus, UsbVidPid(VENDOR_ID, PRODUCT_ID))
            .manufacturer("lujoga")
            .product("faderboard")
            .max_power(500)
            .build();

        Usb { usb_dev, serial }
    }

    pub fn poll(&mut self) {
        if self.usb_dev.poll(&mut [&mut self.serial]) {
            let mut buf = [0u8; 64];
            if let Ok(count) = self.serial.read(&mut buf[..]) {
                let _ = self.serial.write(&buf[..count]);
            }
        }
    }
}
