// includes

#include <stdarg.h>
#include <sys/time.h>
#include "util.h"
#include "log.h"

// variables

log_t LogDefault[1];
log_t LogDump[1];

// functions

void Log(char *fmt, ...){
   va_list ap;
   char buf[MAXSTR];
   va_start(ap, fmt);
   vsnprintf(buf, MAXSTR-1, fmt, ap);
   va_end(ap);
   LogString(LogDefault, buf);
}

void LogInit(log_t *logger){
    logger->filename=NULL;
    logger->ofp=NULL;
    logger->state=false;
    logger->timestamp=false;
    logger->append=false;
    logger->was_newline=true;
    logger->newline_prefix=NULL;
    my_string_set(&logger->newline_prefix,"");
    my_string_set(&logger->banner,"");
}


void LogClear(log_t *logger){
    if(logger->ofp){
	fclose(logger->ofp);
    }
    LogInit(logger);
}

void LogSetFile(log_t *logger, const char *filename){
    if(logger->ofp){
	fclose(logger->ofp);
	logger->ofp=NULL;
    }
    my_string_set(&logger->filename,filename);
}

void LogSetNewlinePrefix(log_t *logger, const char *s){
    my_string_set(&logger->newline_prefix,s);
}

void LogEnsureNewline(log_t *logger){
    if(!logger->was_newline){
	logger->was_newline=true;
    }
}

void LogSetState(log_t *logger, int state){
    logger->state=state;
    if(logger->ofp){
	fclose(logger->ofp);
	logger->ofp=NULL;
    }
}

void LogSetAppend(log_t *logger, int append){
    logger->append=append;
    if(logger->ofp){
	fclose(logger->ofp);
	logger->ofp=NULL;
    }
}

void LogSetTimeStamp(log_t *logger, int timestamp){
    logger->timestamp=timestamp;
}

void LogString(log_t *logger, char *fmt, ...){
    struct timeval tv;
    char buf1[MAXSTR];
    char s[MAXSTR];
    int i=0;
    char c;
    
    
    if(!logger->state){ 
	return;
    }
    
    if(!logger->filename){
	return;
    }
    
    if(!logger->ofp){
	if(logger->append){
	    logger->ofp=fopen(logger->filename,"a");
	}else{
	    logger->ofp=fopen(logger->filename,"w");
	}
	if(!logger->ofp){
	    return;
	}
	fprintf(logger->ofp,"%s\n",logger->banner);
    }
    
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(s, MAXSTR-1, fmt, ap);
    va_end(ap);

    while((c=s[i++])!='\0'){
	if(logger->was_newline){
	    if(logger->timestamp){
		gettimeofday(&tv, NULL);
		sprintf(buf1, "%010ld.%06ld: ", tv.tv_sec, tv.tv_usec);
		fprintf(logger->ofp, "%s",buf1);
		fflush(logger->ofp);
		logger->was_newline=false;
	    }
	    fprintf(logger->ofp, "%s",logger->newline_prefix);
	}
	fprintf(logger->ofp,"%c",c);
	if(c=='\n'){
	    logger->was_newline=true;
	}
    }
    // XXX
    //fflush(logger->ofp);
}     

