#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/time.h>
#include <fcntl.h>

#include "global.h"
#include "message.h"
#include "log.h"
#include "sql_query.h"

tErr readStdinUntilHeader(tMsg* msg){
#ifdef debug
	int fp;
#endif
	char inbuff[STDIN_BUFFSIZE];
	int sizeRead;
	unsigned int oldSize;


	msg->m_size=0;
#ifdef debug
	fp = open("/root/testmail",O_RDONLY,0);
	if(!fp)	fprintf(stderr,"Openfine failed!!!\n");
	while( (sizeRead = read(fp,inbuff,sizeof(inbuff))) > 0 ){
#else
	while( (sizeRead = read(0,inbuff,sizeof(inbuff))) > 0 ){
#endif
		oldSize = msg->m_size;
		if( (msg->m_message = (char*)realloc(msg->m_message,msg->m_size+sizeRead+1)) == NULL){
			return(OUT_OF_MEM);
		}
		memcpy(msg->m_message+msg->m_size,inbuff,sizeRead);
		msg->m_size += sizeRead;
		msg->m_message[msg->m_size+1] = 0;

		// Stop if end of buffer reached
		if(msg->m_size > 3){
			if(oldSize < 3){
				if( strstr(msg->m_message,"\r\n\r\n") ){
					return noErr;
				}
			}else{
				if( strstr(msg->m_message+oldSize-3,"\r\n\r\n") ){
					return noErr;
				}
			}
		}
	}
	if(sizeRead < 0){
		fprintf(stderr,"read() returned -1\n");
		return(INCONSISTENT_MESSAGE);
	}
	if(msg->m_size<20){
		fprintf(stderr,"Message size less than 20 bytes\n");
		return(INCONSISTENT_MESSAGE);
	}
#ifdef debug
	close(fp);
#endif
	return noErr;
}

char* readMessage(tMsg* msg){
	char inbuff[STDIN_BUFFSIZE];
	int sizeRead;

	while( (sizeRead = read(0,inbuff,sizeof(inbuff))) > 0 ){
		if( (msg->m_message = (char*)realloc(msg->m_message,msg->m_size+sizeRead+1)) == NULL)
			return(NULL);
		memcpy(msg->m_message+msg->m_size,inbuff,sizeRead);
		msg->m_size += sizeRead;
		msg->m_message[msg->m_size+1] = 0;
	}
	if(sizeRead < 0){
		return NULL;
	}
	return msg->m_message;
}

tErr initMessage(tMsg* msg){
	tErr err;

	msg->m_message = NULL;
	msg->m_head = NULL;
	msg->m_size = 0;

	if( (err = readStdinUntilHeader(msg)) != noErr)
		return err;
	if( (msg->m_head = (header*)malloc(sizeof(header))) == NULL)
		return OUT_OF_MEM;
	err = initHeader(msg->m_head,&msg->m_message,&msg->m_size);
	return err;
}

void destroyMessage(tMsg* msg){
	if(msg->m_head != NULL)		destroyHeader(msg->m_head);
	if(msg->m_message != NULL)	free(msg->m_message);
}
