#include <glib.h>

#include "edvtypes.h"
#include "edvmimetypes.h"
#include "edvcontext.h"
#include "edvmimetypesinstall.h"
#include "config.h"


void EDVMimeTypeInstall(
	edv_context_struct *ctx,
	edv_mimetype_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 calling function should map the Endeavour MIME Types
 *	Window by a call to EDVWindowMIMETypesWindowMap() to ensure
 *	that Endeavour is running before calling this function.
 *
 *	The given MIME Type m will not be modified or deleted by
 *	this function.
 */
void EDVMimeTypeInstall(
	edv_context_struct *ctx,
	edv_mimetype_struct *m
)
{
	gint i;
	const gchar *s;
	gchar *cmd;

	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 icon file paths */
	for(i = 0; i < EDV_MIMETYPE_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_MIMETYPE_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_MIMETYPE_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 commands */
	for(i = 0; i < m->total_commands; i++)
	{
	    s = m->command_name[i];
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");

	    s = m->command[i];
	    cmd = G_STRCAT(cmd, " \"");
	    if(s != NULL)
		cmd = G_STRCAT(cmd, s);
	    cmd = G_STRCAT(cmd, "\"");
	}


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

