/*
 * 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 {
	MESSAGE_END,
	MESSAGE_INTEGER,
	MESSAGE_STRING,
	MESSAGE_SKIP
} MESSAGE_ITEM_TYPE;

struct s_message_item {
	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 message_from_stream() */
	int state;
	GString *token;
} MESSAGE;

typedef void (*MESSAGE_HANDLER)(MESSAGE *);

/* message infrastructure initialization */
void message_init(void);
	
/* create empty message */
MESSAGE *message_create(char src, char dest);
	
/* destroy message */
void message_destroy(MESSAGE *msg);

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

/* append data into message */
int message_append(MESSAGE *msg, ...);

/* get data from message 
 *
 * rewind:	-1	get from begin, do not rewind
 * 		 0 	do not rewind, get next
 * 		+1	rewind to begin, then get next
 */
int message_get_next(MESSAGE *msg, int rewind, ...);
#define message_get(msg,args...) message_get_next((msg), -1, ##args)

/* create message from string */
MESSAGE *message_from_string(char src, char dest, const char *str, char **p);

/* create message from stream of chars, see message_from_string for details */
int message_from_stream(char src, char dest, char ch, MESSAGE **msg);

/* convert message to string */
char *message_to_string(MESSAGE *msg, int append_nl);

/* stream message to file */
int message_to_file(MESSAGE *msg, FILE *file, int append_nl);

/* send message */
int message_send(MESSAGE *msg);

/* register target for messages (callback) */
int message_register_target(char dest, MESSAGE_HANDLER handle);

#endif

