#include <glib.h>

#include "../include/disk.h"

#include "endeavour2.h"
#include "edv_open_cb.h"
#include "edv_open.h"


edv_open_cb_data_struct *EDVOpenCBDataNew(void);
void EDVOpenCBDataDelete(edv_open_cb_data_struct *d);

void EDVOpenCB(GtkWidget *widget, gpointer data);


#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)


edv_open_cb_data_struct *EDVOpenCBDataNew(void)
{
	return(EDV_OPEN_CB_DATA(g_malloc0(sizeof(edv_open_cb_data_struct))));
}

void EDVOpenCBDataDelete(edv_open_cb_data_struct *d)
{
	if(d == NULL)
	    return;

	g_free(d->command_name);
	g_free(d);
}


void EDVOpenCB(GtkWidget *widget, gpointer data)
{
	GList *paths_list;
	edv_open_cb_data_struct *d = EDV_OPEN_CB_DATA(data);
	if(d == NULL)
	    return;

	/* Get the list of selected paths */
	if(d->paths_list_get_cb != NULL)
	    paths_list = d->paths_list_get_cb(
		d->paths_list_get_data
	    );
	else
	    paths_list = NULL;

	if(paths_list != NULL)
	{
	    const gchar *path;
	    GList *glist = g_list_last(paths_list);
	    if(glist == NULL)
		glist = paths_list;
	    path = (const gchar *)glist->data;
	    if(ISPATHDIR(path))
	    {
		if(d->goto_directory_cb != NULL)
		    d->goto_directory_cb(
			d->goto_directory_data,
			path
		    );
	    }
	    else
	    {
		/* Open the paths */
		EDVOpen(
		    d->core,
		    paths_list,
		    d->command_name,
		    d->toplevel,
		    d->verbose,
		    NULL, NULL
		);
	    }
	}

	/* Delete the list of selected paths */
	g_list_foreach(paths_list, (GFunc)g_free, NULL);
	g_list_free(paths_list);
}
