/*
 * drv_usb_vport.c
 *
 *  Created on: Feb 2, 2012
 *      Author: tkl
 */

#include <stdint.h>
#include <string.h>

#include "usb_vport.h"

//-----------------------------------------------------------------------------
struct {
	const void	*callback;
	const void	*parameter;
	char *buffer;
	unsigned int size;
}usb_vport_obj;

//------------------------------------------------------------------------------
typedef void* (*stm32_usb_vport_cb_t)(const void*);

//------------------------------------------------------------------------------
int stm32_usb_vport_init(const stm32_usb_vport_t *this) {
	usb_vport_obj.callback = NULL;
	usb_vport_obj.parameter = NULL;
	usb_vport_obj.buffer = NULL;
	usb_vport_obj.size = 0;
	return 0;
}

//-----------------------------------------------------------------------------
int stm32_usb_vport_open(const void *this) {
//    USBD_Init(&USB_OTG_dev, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_CDC_cb, &USR_cb);

    return 1;
}

//-----------------------------------------------------------------------------
int stm32_usb_vport_close(const void *this) {
    return 0;
}

//-----------------------------------------------------------------------------
int stm32_usb_vport_read(const void *this, char *buffer, int size) {
	int ret = -1;
	if(size >= usb_vport_obj.size) {
		// no rest
		memcpy(buffer, usb_vport_obj.buffer, usb_vport_obj.size);
		usb_vport_obj.buffer = NULL;
		ret = usb_vport_obj.size;
		usb_vport_obj.size = 0;
	}
	else if(size < usb_vport_obj.size) {
		memcpy(buffer, usb_vport_obj.buffer, size);
		usb_vport_obj.buffer += size;
		usb_vport_obj.size -= size;
		ret = size;
		/*
		if(NULL != usb_vport_obj.callback) {
			stm32_usb_vport_cb_t cb = usb_vport_obj.callback;
			cb(usb_vport_obj.parameter);
		}
		*/
	}
	return ret;
}

//-----------------------------------------------------------------------------
int stm32_usb_vport_write(const void *this, const char *buffer, int size) {
	return USB_VCOM_Send((char *)buffer, size);
}

//-----------------------------------------------------------------------------
int stm32_usb_vport_set_cb(const void *this, const void *callback, const void *param) {
	if(NULL == callback) {
		return -1;
	}
	usb_vport_obj.callback = callback;
	usb_vport_obj.parameter = param;
	return 0;
}

//-----------------------------------------------------------------------------
extern void data_in(unsigned char *buffer, unsigned int size) {
	if(NULL != usb_vport_obj.callback) {
		stm32_usb_vport_cb_t cb = usb_vport_obj.callback;
		usb_vport_obj.buffer = (char *)buffer;
		usb_vport_obj.size = size;
		cb(usb_vport_obj.parameter);
	}
}
