#include <stdio.h>
#include <stdlib.h>
#include <libesmtp.h>
#include <string.h>

#include "smtp.h"

#define TRUE 1
#define FALSE 0

typedef struct{
	char *message;
	int called;
}msg;

void monitor_cb (const char *buf, int buflen, int writing, void *arg){
	FILE *fp = (FILE*)arg;

	if (writing == SMTP_CB_HEADERS){
		fputs ("H: ", fp);
		fwrite (buf, 1, buflen, fp);
		return;
	}

	fputs (writing ? "C: " : "S: ", fp);
	fwrite (buf, 1, buflen, fp);
	if (buf[buflen - 1] != '\n')
		putc ('\n', fp);
}

static const char * print_message(void **buf,int *len,msg *message){
	*buf=NULL;
	if(len!=NULL){
		if(!message->called){
			message->called=TRUE;
			*len=strlen(message->message);
			return message->message;
		}else
			return NULL;
	}
	return NULL;
}

void ESMTP_send_message(const char *username,const char *from,const char *recipient,const char *subject,const char *messagebody){
	smtp_session_t session;
	smtp_message_t message;
	msg m={NULL,FALSE};

//	printf("\n\nUsername:%s, From:%s, To:%s, Subject:%s, Body:%s",username,from,recipient,subject,messagebody);

	m.message=(char*)malloc(strlen(messagebody)+strlen("\r\n")+1);
	strcpy(m.message,"\r\n");
	strcat(m.message,messagebody);

	session=smtp_create_session();
	message=smtp_add_message(session);
	smtp_set_server(session,"localhost:25");
	smtp_set_header(message,"From",username,from);
	smtp_set_header(message,"Subject",subject);
	smtp_add_recipient(message,recipient);
	smtp_set_messagecb(message,(smtp_messagecb_t)print_message,&m);
	if(!smtp_start_session(session)){
		char buf[1024];
		fprintf (stderr, "SMTP server problem %s\n",smtp_strerror (smtp_errno (), buf, sizeof buf));
	}
	smtp_destroy_session(session); /* seg.fault here */
	free(m.message);
}
