/*
 * nb_message.h
 * 
 * Copyright (C) 2006-2007  Josef Kufner <jk@myserver.cz>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */
#ifndef JK_MESSAGE_H
#define JK_MESSAGE_H

#include <glib.h>
#include <stdio.h>

typedef enum {
	NB_MESSAGE_END,
	NB_MESSAGE_INTEGER,
	NB_MESSAGE_STRING,
	NB_MESSAGE_SKIP
} NB_MESSAGE_ITEM_TYPE;

typedef enum {
	NB_MESSAGE_GET_REWIND = 0x10,	/* rewind list to begin */
	NB_MESSAGE_GET_BEGIN = 0x20,	/* get from begin, do no rewind */
	NB_MESSAGE_GET_NEXT = 0x00	/* get next */
} NB_MESSAGE_GET_FLAG;

struct s_message_item {
	NB_MESSAGE_ITEM_TYPE type;
	union {
		int integer;
		char *string;
	} value;
	struct s_message_item *next;
};

typedef struct {
	char src, dest;
	struct s_message_item *list, *p_list_end, *p_list_next;
	int length;

	/* for nb_message_from_stream() */
	int state;
	GString *token;
} NB_MESSAGE;

typedef void (*NB_MESSAGE_HANDLER)(NB_MESSAGE *);

/* nb_message infrastructure initialization */
void nb_message_init(void);
	
/* create empty nb_message */
NB_MESSAGE *nb_message_create(char src, char dest);
	
/* destroy nb_message */
void nb_message_destroy(NB_MESSAGE *msg);

/* modify src and/or dest (zero = don't change) */
void nb_message_edit(NB_MESSAGE *msg, char src, char dest);

/* append data into nb_message */
int nb_message_append(NB_MESSAGE *msg, ...);

/* get data from nb_message 
 *
 * rewind:	-1	get from begin, do not rewind
 * 		 0 	do not rewind, get next
 * 		+1	rewind to begin, then get next
 */
int nb_message_get_next(NB_MESSAGE *msg, NB_MESSAGE_GET_FLAG rewind, ...);
#define nb_message_get(msg,args...) nb_message_get_next((msg), NB_MESSAGE_GET_NEXT, ##args)

/* create nb_message from string */
NB_MESSAGE *nb_message_from_string(char src, char dest, const char *str, char **p);

/* create nb_message from stream of chars, see nb_message_from_string for details */
int nb_message_from_stream(char src, char dest, char ch, NB_MESSAGE **msg);

/* convert nb_message to string */
char *nb_message_to_string(NB_MESSAGE *msg, int append_nl);

/* stream nb_message to file */
int nb_message_to_file(NB_MESSAGE *msg, FILE *file, int append_nl);

/* send nb_message */
int nb_message_send(NB_MESSAGE *msg);

/* register target for nb_messages (callback) */
int nb_message_register_target(char dest, NB_MESSAGE_HANDLER handle);

#endif

