/*
 * process.c
 * 
 * Copyright (C) 2006  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.
 *
 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>

#include "main.h"	/* includes loudmouth and glib */
#include "process.h"
#include "message.h"


static void process_stdin_message(MESSAGE *msg)
{
	char *cmd;

	/* get command */
	if (message_get(msg, MESSAGE_PART_DATA, MESSAGE_STRING, &cmd, MESSAGE_END)) {
		/* append sender info */
		message_destroy_part(msg, MESSAGE_PART_SENDER_INFO);
		message_append(msg, MESSAGE_PART_SENDER_INFO, MESSAGE_STRING, dummy_name, MESSAGE_INTEGER, 0, MESSAGE_END);

		/* process command */
		switch(cmd[0]) {
			case 'C':
				print_msg(D_DEBUG, "Chat message...");
				message_to_file(msg, stdout, 1);
				break;

			case 'S':
				print_msg(D_DEBUG, "Session control message...");
				message_to_file(msg, stdout, 1);
				break;

			case 'T':
				switch (cmd[1]) {
					case 'p': /* ping */
						{
							MESSAGE *msg;
							print_msg(D_DEBUG, "Ping.");
							msg = message_create(0, 0);
							message_append(msg, MESSAGE_PART_DATA, 
								MESSAGE_STRING, "Tr",
								MESSAGE_END);
							message_to_file(msg, stdout, 0);
							message_destroy(msg);
						}
						break;
				}
		}
	}
}


int process_stdin(const char *message)
{
	static MESSAGE *msg;
	const char *p;
	char *str;
	
	assert(message != NULL);
	
	print_msg(D_DEBUG, "Parsing data...");
	for (p = message; *p; p++) {
		if (message_from_stream('N', 0, *p, &msg) == 1) {
			/* debug */
			if (D_DEBUG <= verbose) {
				str = message_to_string(msg, 0);
				print_msg(D_DEBUG, "Received message: %s", str);
				free(str);
			}

			/* process message */
			process_stdin_message(msg);
			message_destroy(msg);
			msg = NULL;
		}
	}
	return 0;
}


/* vim:set encoding=utf8: */
