#include <string.h>
#include <glib.h>
#include "edvutils.h"
#include "edvdevices.h"
#include "edvcontext.h"
#include "edvdevicesget.h"


edv_device_struct **EDVDevicesList(
	edv_context_struct *ctx, gint *total
);
edv_device_struct *EDVDeviceMatch(
	edv_context_struct *ctx, const gchar *path
);


#define ATOI(s)         (((s) != NULL) ? atoi(s) : 0)
#define ATOL(s)         (((s) != NULL) ? atol(s) : 0)
#define ATOF(s)         (((s) != NULL) ? atof(s) : 0.0f)
#define STRDUP(s)       (((s) != NULL) ? g_strdup(s) : NULL)

#define MAX(a,b)        (((a) > (b)) ? (a) : (b))
#define MIN(a,b)        (((a) < (b)) ? (a) : (b))
#define CLIP(a,l,h)     (MIN(MAX((a),(l)),(h)))
#define STRLEN(s)       (((s) != NULL) ? strlen(s) : 0)
#define STRISEMPTY(s)   (((s) != NULL) ? (*(s) == '\0') : TRUE)


/*
 *	Returns a list of Devices.
 *
 *	The returned list must not be modified or deleted.
 */
edv_device_struct **EDVDevicesList(
	edv_context_struct *ctx, gint *total
)
{
	if(total != NULL)
	    *total = 0;

	if(ctx == NULL)
	    return(NULL);

	if(total != NULL)
	    *total = ctx->total_devices;

	return(ctx->device);
}

/*
 *      Matches the object specified by path with a Device who has 
 *      the same mount path or device path.
 *
 *      Returns the matched Device or NULL on error, the returned
 *      Device must not be modified or deleted.               
 */
edv_device_struct *EDVDeviceMatch(
	edv_context_struct *ctx, const gchar *path
)
{
	gint i, total;
	edv_device_struct *d, **list;

	if((ctx == NULL) || STRISEMPTY(path))
	    return(NULL);

	/* Get Devices list */
	list = ctx->device;
	total = ctx->total_devices;
	if(list == NULL)
	    return(NULL);

	/* Iterate through the Devices list */
	for(i = 0; i < total; i++)
	{
	    d = list[i];
	    if(d == NULL)
		continue;

	    if(!STRISEMPTY(d->device_path))
	    {
		if(!strcmp(d->device_path, path))
		    return(d);
	    }

	    if(!STRISEMPTY(d->mount_path))
	    {
		if(!strcmp(d->mount_path, path))
		    return(d);
	    }
	}

	return(NULL);
}
