#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 "my_strings.h"

tErr tMsg::readStdinUntilHeader(){
	char inbuff[STDIN_BUFFSIZE];
	int sizeRead;
	unsigned int oldSize;

	m_size=0;
#ifdef staticfile
	int fp;
	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 = m_size;
		if( (m_message = (char*)realloc(m_message,m_size+sizeRead+1)) == NULL){
			return(OUT_OF_MEM);
		}
		memcpy(m_message+m_size,inbuff,sizeRead);
		m_size += sizeRead;
		m_message[m_size] = 0;

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

char* tMsg::readMessage(){
	return m_message;
/*	char inbuff[STDIN_BUFFSIZE];
	unsigned int sizeRead;


	while( (sizeRead = read(0,inbuff,sizeof(inbuff))) > 0 ){
		printf("\ntest\n");
		if( (m_message = (char*)realloc(m_message,m_size+sizeRead+1)) == NULL){
			return NULL;
		}
		memcpy(m_message+m_size,inbuff,sizeRead);
		m_size += sizeRead;
		m_message[m_size+1] = 0;
	}
	printf("\ntest2\n");
	return m_message;
*/
}

tErr tMsg::init(){
	tErr err;
	if( (err = readStdinUntilHeader()) != noErr) return err;
	m_message = lf2crlf(m_message,&m_size);
//	m_size = strlen(m_message);
	if( (m_head = new  header()) == NULL) return OUT_OF_MEM;
	err = m_head->init(&m_message,&m_size);
	return err;
}
