/*
 * Copyright (c) 2004-2009, Luiz Otavio O Souza <loos.br@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * $Id: command.h 98 2009-01-24 17:23:36Z loos-br $
 */

#ifndef COMMAND_H
#define COMMAND_H

#include "string.h"

#define	CMD_BUF		512

#define	RECVMASK	0x00ff
#define	COMMAND		0x0001
#define	PAYLOAD		0x0002
#define	ARG		0x0004
#define	EOC		0x0008
#define	SENDMASK	0xff00
#define	SENDDELAY	0x0100

typedef struct _command {
    int			ignore;
    int			fase;
    string		obuf;
    string		cmd;
    string		**args;
    string		payload;
    unsigned int	args_len;
    unsigned long	trid;
    struct _command	*next;
} command;

typedef struct _commands {
    string		buf;		/* io command buffer */
    string		*arg;		/* tmp pointer to last arg */
    __uint32_t		wait;		/* trid to wait */
    __uint32_t		state;		/* command state */
    __uint32_t		payload_size;	/* payload size */
    struct _command	*tmp;		/* tmp pointer to ongoing command */
    struct _command	*cmd;		/* linked list to ready commands */
    struct _command	*cmd_last;	/* pointer to last entry on list */
} commands;

#define	HAS_CMD(p) (p->commands.cmd != NULL)

command		*command_alloc(void);
__uint32_t	has_payload(command *cmd);
string		**args_alloc(void *ptr, size_t len);
string		*command_add_arg(command *cmd);
void		has_trid(command *cmd);
void		free_command(command *cmd);
void		print_command(command *cmd);
void		commands_init(commands *cmds);
void		free_command_args(command *cmd);
void		print_client_command(string *email, command *cmd);
void		print_server_command(string *email, command *cmd);
void		commands_add_command(commands *cmds, command *cmd);
int		send_command(int tofd, command *cmd, string *email, const char *to);
int		read_command(commands *cmds, int fd, void (*sched_write)(), void *ev_write);

#endif
