#include <glib.h>

#include "edv_types.h"
#include "edv_mime_type.h"
#include "edv_context.h"
#include "edv_mime_type_install.h"
#include "config.h"


void EDVMimeTypeInstall(
	edv_context_struct *ctx, edv_mime_type_struct *m
);


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


static gchar *G_STRCAT(gchar *s, const gchar *s2)
{ 
	if(s != NULL) {
	    if(s2 != NULL) {
		gchar *sr = g_strconcat(s, s2, NULL);
		g_free(s);
		s = sr;
	    }
	} else {
	    if(s2 != NULL)
		s = STRDUP(s2);
	    else
		s = STRDUP("");
	}
	return(s);
}


/*
 *	Installs a new MIME Type.
 *
 *	The m specifies the MIME Type to be installed. It will not be
 *	modified or deleted by this call.
 *
 *	The calling function should map the Endeavour MIME Types
 *	Window by a call to EDVWindowMIMETypesWindowMap() to ensure
 *	that Endeavour is running before calling this function.
 */
void EDVMimeTypeInstall(
	edv_context_struct *ctx, edv_mime_type_struct *m
)
{
	gint i;
	const gchar *s;
	gchar *cmd;
	GList *glist;
	edv_mime_type_command_struct *mcmd;

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

	cmd = g_strdup_printf(
"install_mimetype %i \"%s\" \"%s\" \"%s\" %i",
	    m->mt_class,
	    m->type,
	    m->value,
	    m->description,
	    m->handler
	);

	/* Append the icon file paths */
	for(i = 0; i < EDV_MIME_TYPE_TOTAL_ICON_STATES; i++)
	{
	    s = m->small_icon_file[i];
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");
	}
	for(i = 0; i < EDV_MIME_TYPE_TOTAL_ICON_STATES; i++)
	{
	    s = m->medium_icon_file[i];
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");
	}
	for(i = 0; i < EDV_MIME_TYPE_TOTAL_ICON_STATES; i++)
	{
	    s = m->large_icon_file[i];
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");
	}

	/* Append the commands */
	for(glist = m->commands_list; glist != NULL; glist = g_list_next(glist))
	{
	    mcmd = EDV_MIME_TYPE_COMMAND(glist->data);
	    if(mcmd == NULL)
		continue;

	    s = mcmd->name;
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");

	    s = mcmd->command;
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");
	}

	EDVContextQueueCommand(ctx, cmd);
	g_free(cmd);
}
