/*
Copyright 1990-2005 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <sys/mman.h>
#include <sys/stat.h>

#include "imbean.h"

#define ELEMENT_INITIAL_SIZE      6
#define ELEMENT_INCREASE_SIZE     6

#define IBML_ERR_STR_DEFAULT                     "IBML Parser Error"
#define IBML_ERR_STR_NO_MEMORY                   "IBML Error:  No Memory"
#define IBML_ERR_STR_INVALID_ELEMENT_NAME        "IBML Error:  Invalid Element Name"
#define IBML_ERR_STR_INVALID_ELEMENT_ATTRIBUTE   "IBML Error:  Invalid Element Property"
#define IBML_ERR_STR_INVALID_ELEMENT_ITEM        "IBML Error:  Invalid Element Item"

enum {
	IBML_ERR_OK = 0,
	IBML_ERR_NO_MEMORY,
	IBML_ERR_INVALID_ELEMENT_NAME,
	IBML_ERR_INVALID_ELEMENT_ATTRIBUTE,
	IBML_ERR_INVALID_ELEMENT_ITEM,
};

#define SafeFree(pointer)               if(pointer) free((char *)(pointer))

static IbmlProperty *ibml_property_new()
{
	IbmlProperty *ibml_property;

	ibml_property = (IbmlProperty *)malloc(sizeof(IbmlProperty));
	if (ibml_property == NULL) return(NULL);

	ibml_property->name = NULL;
	ibml_property->type = NULL;
	ibml_property->value = NULL;
	ibml_property->options = NULL;
	ibml_property->scope = NULL;

	return(ibml_property);
}

static int ibml_property_free(IbmlProperty *ibml_property)
{
	if (ibml_property == NULL) return(IBML_OK);

	SafeFree(ibml_property->name);
	SafeFree(ibml_property->type);
	SafeFree(ibml_property->value);
	SafeFree(ibml_property->options);
	SafeFree(ibml_property->scope);

	SafeFree(ibml_property);

	return(IBML_OK);
}

static int ibml_property_print(IbmlProperty *ibml_property)
{
	char *name;
	char *type;
	char *value;
	char *options;
	char *scope;

	if (ibml_property == NULL) return(IBML_OK);

	name = ibml_property->name;
	type = ibml_property->type;
	value = ibml_property->value;
	options = ibml_property->options;
        scope = ibml_property->scope;
	if (name && value) {
		printf("    name: %s, value: %s,  ", name, value);
		if (type)
			printf("type: %s  ", type);
		if (options)
			printf("options: %s  ", options);
		if (scope)
			printf("scope: %s  ", scope);
		printf ("\n");
	}

	return(IBML_OK);
}

static IbmlElement *ibml_element_new()
{
	IbmlElement *ibml_element;

	ibml_element = (IbmlElement *)malloc(sizeof(IbmlElement));
	if (ibml_element == NULL) return(NULL);

	ibml_element->id = NULL;
	ibml_element->scope = NULL;
	ibml_element->class = NULL;

	ibml_element->num_properties = 0;
	ibml_element->properties = NULL;

	return(ibml_element);
}

static int ibml_element_free(IbmlElement *ibml_element)
{
	int i;

	if (ibml_element == NULL) return(IBML_OK);

	SafeFree(ibml_element->id);
	SafeFree(ibml_element->scope);
	SafeFree(ibml_element->class);

	for (i=0; i<ibml_element->num_properties; i++)
		ibml_property_free(ibml_element->properties[i]);
	SafeFree(ibml_element->properties);

	SafeFree(ibml_element);

	return(IBML_OK);
}

static int ibml_element_print(IbmlElement *ibml_element)
{
	int i;
	char *id;

	if (ibml_element == NULL) return(IBML_OK);

	id = ibml_element->id;
	if (id && *id)
		printf("  id: %s\n", id);

	for (i=0; i<ibml_element->num_properties; i++)
		ibml_property_print(ibml_element->properties[i]);

	return(IBML_OK);
}

IbmlCatagory *ibml_catagory_new()
{
	IbmlCatagory *ibml_catagory;

	ibml_catagory = (IbmlCatagory *)malloc(sizeof(IbmlCatagory));
	if (ibml_catagory == NULL) return(NULL);

	ibml_catagory->num_elements = 0;
	ibml_catagory->elements = NULL;

	return(ibml_catagory);
}

int ibml_catagory_free(IbmlCatagory *ibml_catagory)
{
	int i;

	if (ibml_catagory == NULL) return(IBML_OK);

	for (i=0; i<ibml_catagory->num_elements; i++)
		ibml_element_free(ibml_catagory->elements[i]);
	SafeFree(ibml_catagory->elements);

	SafeFree(ibml_catagory->scope);
	SafeFree(ibml_catagory);

	return(IBML_OK);
} 

int ibml_catagory_print(IbmlCatagory *ibml_catagory)
{
	int i;
	char *scope;

	if (ibml_catagory == NULL) return(IBML_OK);

	scope = ibml_catagory->scope;
	if (scope && *scope)
		printf("Catagory: %s\n", scope);

	for (i=0; i<ibml_catagory->num_elements; i++)
		ibml_element_print(ibml_catagory->elements[i]);

	return(IBML_OK);
} 

IbmlData *ibml_data_new()
{
	IbmlData *ibml_data;

	ibml_data = (IbmlData *)malloc(sizeof(IbmlData));
	if (ibml_data == NULL) return(NULL);

	ibml_data->num_catagories = 0;
	ibml_data->catagories = NULL;

	return(ibml_data);
}

int ibml_data_free(IbmlData *ibml_data)
{
	int i;

	if (ibml_data == NULL) return(IBML_OK);

	for (i=0; i<ibml_data->num_catagories; i++)
		ibml_catagory_free(ibml_data->catagories[i]);
	SafeFree(ibml_data->catagories);

	SafeFree(ibml_data);

	return(IBML_OK);
} 

int ibml_data_print(IbmlData *ibml_data)
{
	int i;

	if (ibml_data == NULL) return(IBML_OK);

	for (i=0; i<ibml_data->num_catagories; i++)
		ibml_catagory_print(ibml_data->catagories[i]);

	return(IBML_OK);
} 

static char *ibml_strdup(char *str)
{
	char  *ptr;

	ptr = (char *)calloc(strlen(str) + 1, 1);
	if (ptr != NULL) strcpy(ptr, str);

	return (ptr);
}

static char *get_error_message(int error_no)
{
	switch (error_no) {
		case IBML_ERR_NO_MEMORY:
			return(IBML_ERR_STR_NO_MEMORY);
		case IBML_ERR_INVALID_ELEMENT_NAME:
			return(IBML_ERR_STR_INVALID_ELEMENT_NAME);
		case IBML_ERR_INVALID_ELEMENT_ATTRIBUTE:
			return(IBML_ERR_STR_INVALID_ELEMENT_ATTRIBUTE);
		case IBML_ERR_INVALID_ELEMENT_ITEM:
			return(IBML_ERR_STR_INVALID_ELEMENT_ITEM);
	}
	return(IBML_ERR_STR_DEFAULT);
}

static int num_properties_alloced = 0;
int parseImbeanProperty(xmlDocPtr doc, xmlNodePtr cur, IbmlElement *ibml_element)
{
	xmlChar *property_name = NULL;
	xmlChar *property_value = NULL;
	xmlChar *property_scope = NULL;
	xmlChar *property_options = NULL;
	xmlChar *property_type = NULL;

	IbmlProperty *ibml_property;
	int i;

	if (ibml_element->num_properties % ELEMENT_INITIAL_SIZE == 0) {
        	if (num_properties_alloced == 0) {
			/* Alloc memory for Initial elements */
			num_properties_alloced = ELEMENT_INITIAL_SIZE;
			ibml_element->properties = (IbmlPropertyPtr *)malloc(num_properties_alloced * sizeof(IbmlPropertyPtr));
		} else {
			/* realloc the buffer for the elements list */
			num_properties_alloced += ELEMENT_INITIAL_SIZE;
			ibml_element->properties = (IbmlPropertyPtr *)realloc(ibml_element->properties, num_properties_alloced * sizeof(IbmlPropertyPtr));
		}
		if (ibml_element->properties == NULL) {
			ibml_element->num_properties = 0;
			return(IBML_ERROR);
		}
		for (i=ibml_element->num_properties; i<num_properties_alloced; i++) {
			ibml_element->properties[i] = NULL;
		}
	}

	ibml_property = (IbmlProperty *)ibml_property_new();
	if (ibml_property == NULL) {
		return(IBML_ERROR);
	}

	ibml_element->properties[ibml_element->num_properties] = ibml_property;
	ibml_element->num_properties++;

	property_name = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_NAME);
	if (property_name && *property_name)
		ibml_property->name = (char *)ibml_strdup(property_name);
	xmlFree(property_name);

	property_value = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_VALUE);
	if (property_value && *property_value)
		ibml_property->value = (char *)ibml_strdup(property_value);
	xmlFree(property_value);

	property_options = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_OPTIONS);
	if (property_options && *property_options)
		ibml_property->options = (char *)ibml_strdup(property_options);
	xmlFree(property_options);

	property_type = xmlGetProp(cur, IBML_ELEMENT_PROPERTY_TYPE);
	if (property_type && *property_type)
		ibml_property->type = (char *)ibml_strdup(property_type);
	xmlFree(property_type);

	property_scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
	if (property_scope && *property_scope)
		ibml_property->scope = (char *)ibml_strdup(property_scope);
	xmlFree(property_scope);

	return(IBML_OK);
}

static int num_elements_alloced = 0;
int parseImbeanElement(xmlDocPtr doc, xmlNodePtr cur, IbmlCatagory *ibml_catagory)
{
	xmlChar *id = NULL;
	xmlChar *scope = NULL;

	IbmlElement *ibml_element;

	int i;

	if (ibml_catagory->num_elements % ELEMENT_INITIAL_SIZE == 0) {
        	if (num_elements_alloced == 0) {
			/* Alloc memory for Initial elements */
			num_elements_alloced = ELEMENT_INITIAL_SIZE;
			ibml_catagory->elements = (IbmlElementPtr *)malloc(num_elements_alloced * sizeof(IbmlElementPtr));
		} else {
			/* realloc the buffer for the elements list */
			num_elements_alloced += ELEMENT_INITIAL_SIZE;
			ibml_catagory->elements = (IbmlElementPtr *)realloc(ibml_catagory->elements,num_elements_alloced * sizeof(IbmlElementPtr));
		}
		if (ibml_catagory->elements == NULL) {
			ibml_catagory->num_elements = 0;
			return(IBML_ERROR);
		}
		for (i=ibml_catagory->num_elements; i<num_elements_alloced; i++) {
			ibml_catagory->elements[i] = NULL;
		}
	}

	/* Alloc initial memory for item */
	ibml_element = ibml_element_new();
	if (ibml_element == NULL) {
		return(IBML_ERROR);
	}

	ibml_catagory->elements[ibml_catagory->num_elements] = ibml_element;
	ibml_catagory->num_elements ++;

	id = xmlGetProp(cur, IBML_ELEMENT_IMBEAN_ID);
	if (id && *id)
		ibml_element->id = (char *)ibml_strdup(id);
	xmlFree(id);

	scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
	if (scope && *scope)
		ibml_element->scope = (char *)ibml_strdup(scope);
	xmlFree(scope);

	cur = cur->xmlChildrenNode;
	while(cur != NULL) {
		if (!xmlStrcmp(cur->name, (const xmlChar *)IBML_ELEMENT_PROPERTY)) {
			parseImbeanProperty(doc, cur, ibml_element);
		}
		cur = cur->next;
	}

	return(IBML_OK);
}

static int num_catagories_alloced = 0;
int parseImCatagory(xmlDocPtr doc, xmlNodePtr cur, IbmlData *ibml_data)
{
	xmlChar *scope;
	xmlChar *class;

	IbmlCatagory *ibml_catagory;

	int i;

	if (ibml_data->num_catagories % ELEMENT_INITIAL_SIZE == 0) {
        	if (num_catagories_alloced == 0) {
			/* Alloc memory for Initial catagories */
			num_catagories_alloced = ELEMENT_INITIAL_SIZE;
			ibml_data->catagories = (IbmlCatagoryPtr *)malloc(num_catagories_alloced * sizeof(IbmlCatagoryPtr));
		} else {
			/* realloc the buffer for the catagories list */
			num_catagories_alloced += ELEMENT_INITIAL_SIZE;
			ibml_data->catagories = (IbmlCatagoryPtr *)realloc(ibml_data->catagories,num_catagories_alloced * sizeof(IbmlCatagoryPtr));
		}
		if (ibml_data->catagories == NULL) {
			ibml_data->num_catagories = 0;
			return(IBML_ERROR);
		}
		for (i=ibml_data->num_catagories; i<num_catagories_alloced; i++) {
			ibml_data->catagories[i] = NULL;
		}
	}

	/* Alloc initial memory for item */
	ibml_catagory = ibml_catagory_new();
	if (ibml_catagory == NULL) {
		return(IBML_ERROR);
	}

	ibml_data->catagories[ibml_data->num_catagories] = ibml_catagory;
	ibml_data->num_catagories ++;

	scope = xmlGetProp(cur, IBML_ELEMENT_SCOPE);
	if (scope && *scope)
		ibml_catagory->scope = (char *)ibml_strdup(scope);
	xmlFree(scope);

	cur = cur->xmlChildrenNode;
	while(cur != NULL) {
		if (!xmlStrcmp(cur->name, (const xmlChar *)IBML_ELEMENT_IMBEAN)) {
			parseImbeanElement(doc, cur, ibml_catagory);
		}
		cur = cur->next;
	}

	return(IBML_OK);
}

IbmlData *imbean_config_new_from_memory(char *buffer, int size)
{
	xmlDocPtr doc;
	xmlNodePtr cur;

	IbmlData *ibml_data;

	doc = xmlParseMemory(buffer, size);
	if (doc == NULL) {
		return(NULL);
	}

	cur = xmlDocGetRootElement(doc);
	if (cur == NULL) {
		xmlFreeDoc(doc);
		return(NULL);
	}

	if (xmlStrcmp(cur->name, (xmlChar *)IBML_ELEMENT_ROOT)) {
		fprintf(stderr, "wrong root, should be %s\n", IBML_ELEMENT_ROOT);
		xmlFreeDoc(doc);
		return(NULL);
	} 

	ibml_data = ibml_data_new();
	if (ibml_data == NULL) {
		xmlFreeDoc(doc);
		return(NULL);
	}

	cur = cur->xmlChildrenNode;
	while(cur) {
		if (!xmlStrcmp(cur->name, (const xmlChar *)IBML_ELEMENT_CATAGORY)) {
			parseImCatagory(doc, cur, ibml_data);
		}
		cur = cur->next;
	}

	xmlFreeDoc(doc);
	return(ibml_data);
}

IbmlData *imbean_config_new_from_file(char *file_name)
{
	IbmlData *ibml_data;
	FILE *fd;

	struct stat file_stat;
	int file_size;
	const char *base;

	if (stat(file_name, &file_stat) == -1)
		return NULL;

	file_size = file_stat.st_size;
	if (file_size == 0)
		return NULL;

	if ((fd = fopen(file_name, "r")) == NULL)
		return NULL;

	base = (char *)calloc(file_size, sizeof(char));
	if (base == NULL) {
		fclose(fd);
		return NULL;
	}

	if (fread((char *)base, sizeof(char), file_size, fd) != file_size) {
		fclose(fd);
		return NULL;
	}

	ibml_data = (IbmlData *)imbean_config_new_from_memory((char *) base, file_size);

	return(ibml_data);
}
