#include <glib.h>
#include <string.h>
#include <stdlib.h>

#include "entity.h"

static gint
rend_include_file_attr_set (ENode * node, EBuf * attr, EBuf * value)
{
    gchar *filename;

    if (ebuf_not_empty (value)) {
	EDEBUG (("includerend", "file = %s", value->str));
	filename = eutils_file_search (node, value->str);

	if (filename) {
	    /* Set the full path to the file in the include node. */
	    enode_attrib_str (node, "__filename", filename);
	    xml_parse_file (node, filename);
	    g_free (filename);
	} else {
	    gchar *function = enode_attrib_str (node, "onerror", NULL);
	    if (function) {
		/* FIXME: Make a proper error message.. need to fix up the
		 * xml_parse_file * properly first though */
		enode_call_ignore_return (node, function, "s",
					  "Error loading file.");
	    }
	}
    }
    return (TRUE);
}

static void
rend_include_render (ENode * node)
{
    enode_attribs_sync (node);
}

static void
rend_include_parent (ENode * parent_node, ENode * child_node)
{
    /* We have to reparent .. */
    erend_short_curcuit_parent (parent_node, child_node);
}


void
include_renderer_register (void)
{
    Element *element;
    ElementAttr *e_attr;

    element = g_new0 (Element, 1);
    element->parent_func = rend_include_parent;
    element->render_func = rend_include_render;
    element->tag = "include";
    element->description =
	"Load an XML file and render the nodes under this include node.";
    element_register (element);

    e_attr = g_new0 (ElementAttr, 1);
    e_attr->attribute = "file";
    e_attr->description = "Path to XML file to include in place.";
    e_attr->value_desc = "string";
    e_attr->set_attr_func = rend_include_file_attr_set;
    element_register_attrib (element, e_attr);

    e_attr = g_new0 (ElementAttr, 1);
    e_attr->attribute = "onerror";
    e_attr->description = "Function to call when an error occurs";
    e_attr->value_desc = "function";
    e_attr->possible_values = "(node, error_message)";
    element_register_attrib (element, e_attr);

    e_attr = g_new0 (ElementAttr, 1);
    e_attr->attribute = "__filename";
    e_attr->description = "The full path of the file that has been loaded.";
    e_attr->value_desc = "string";
    element_register_attrib (element, e_attr);
}


syntax highlighted by Code2HTML, v. 0.9.1