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

#include "usb-enum.h"

#define	MAX_OUA		16

void oau_display_devarray(struct oau_devarray *ls)
{
	int i;
	for (i = 0; i < ls->ndevs; i++) {
		struct oau_usb_dev *entry = &ls->devs[i];

		printf("%d: busdev:%s:%s bus-port:%s devno:%s serial:%s devpath:%s\n",
			i, entry->busnum, entry->devnum,
			entry->busport, entry->devno, entry->serial, entry->path);
	}
}

static struct oau_usb_dev usb_dev[MAX_OUA];
static struct oau_devarray devarray = { -1, usb_dev, };

struct oau_devarray *oau_get_devarray(char *vendor_id, char *device_id)
{
	struct udev *udev = udev_new();
	struct udev_enumerate *enumerate = udev_enumerate_new(udev);
	struct udev_list_entry *devs, *ptr, *ptr2;
	int found_devs = 0;
	
	udev_enumerate_add_match_property(enumerate, "ID_VENDOR_ID", vendor_id);
	udev_enumerate_add_match_property(enumerate, "ID_MODEL_ID", device_id);
	udev_enumerate_scan_devices(enumerate);
	
	devs = udev_enumerate_get_list_entry(enumerate);
	udev_list_entry_foreach(ptr, devs) {
		if (found_devs >= MAX_OUA)
			goto out;
		const char *path = udev_list_entry_get_name(ptr);
		struct udev_device *dev = udev_device_new_from_syspath(udev, path);
		struct oau_usb_dev *entry = &usb_dev[found_devs];
		strcpy(entry->path, path);
		strcpy(entry->busnum, udev_device_get_sysattr_value(dev, "busnum"));
		strcpy(entry->devnum, udev_device_get_sysattr_value(dev, "devnum"));
		strcpy(entry->devno, udev_device_get_sysattr_value(dev, "dev"));
		strcpy(entry->serial, udev_device_get_sysattr_value(dev, "serial"));
		strcpy(entry->busport, rindex(entry->path, '/') + 1);
		
		found_devs += 1;
		udev_device_unref(dev);
	}
out:
	udev_enumerate_unref(enumerate);
	devarray.ndevs = found_devs;
	return &devarray;
}
