#include <limits.h>
#include <unistd.h>
#include <glib.h>
#include "edvcontext.h"
#include "edvutils.h"
#include "edvopen.h"
#include "config.h"


void EDVOpen(
	edv_context_struct *ctx,
	const gchar *path, const gchar *command_name
);


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


/*
 *      Instructs the Endeavour program to open an object by checking
 *      the object's extension and matching it through its MIME Types
 *      list.  If a method to open the object is found, then that method
 *      will be used to open the object.
 *
 *	If command_name is not NULL then the specific command's name
 *	(defined by the matched MIME Type) will be used (otherwise the
 *	default command will be used).
 *
 *      Typical values for command_name are; "default", "view",
 *      and "edit". However it is difficult to know what the user has
 *      set so it is recommended that command_name be left NULL.
 */
void EDVOpen(
	edv_context_struct *ctx,
	const gchar *path, const gchar *command_name
)
{
	gchar *cmd, *dpath;
	gchar cwd[PATH_MAX];

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

	/* Get copy of evaluated input path */
	dpath = EDVCopyEvaluateInputPath(
	    getcwd(cwd, sizeof(cwd)), path
	);

	/* Format command */
	if(!STRISEMPTY(command_name))
	    cmd = g_strdup_printf(
		"open_object \"%s\" \"%s\"", dpath, command_name
	    );
	else
	    cmd = g_strdup_printf(
		"open_object \"%s\"", dpath
	    );

	/* Queue command */
	EDVContextQueueCommand(ctx, cmd);

	g_free(cmd);
	g_free(dpath);
}
