/*
 * File logger abstraction layer
 *
 * Created by: Sander van Veen <sandervv@gmail.com>,
 *             Taddeüs Kroes <taddeuskroes@gmail.com>
 */
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "logger.h"

/*
 * Initialize a new log handler
 */
log_handler *
create_logger( )
{
	log_handler * log = malloc(sizeof(log_handler));

	log->list = NULL;
	log->count = 0;

	return log;
}

/*
 * Open or create a log file, like fopen(), and add the opened file
 * pointer to the log handler.
 */
FILE *
open_log( const char * filename, const char * access, log_handler * log )
{
	if( !log )
		return NULL;

	log->list = realloc(log->list, (log->count+1) * sizeof(FILE *));
	log->list[log->count] = fopen(filename, access);

	return log->list[log->count++];
}

/*
 * Close a specific log file, which was opened by open_log().
 *
 * See also:
 *   <open_log>, <close_all_logs>
 */
void
close_log( FILE * file, log_handler * log )
{
	if( !file || !log )
		return;

	fclose(file);
	
	FILE ** cur = log->list;

	// Find open file in logger list
	while( *cur != file && cur++ );
	
	if( cur )
	{
		FILE ** end = log->list + log->count;

		free(*cur);
		*cur = NULL;

		for( ; cur < end; cur++ )
			*cur = *(cur+1);

		log->count--;
	}
}

/*
 * Close all log files, which was opened by open_log().
 *
 * See also:
 *   <open_log>, <close_log>
 */
void
close_all_logs( log_handler * log )
{
	if( !log )
		return;
	
	FILE ** cur = log->list;
	FILE ** end = cur + log->count;

	for( ; cur < end; cur++ )
	{
		fclose(*cur);
	}

	free(log->list);
	free(log);
}

void write_to_all_logs( log_handler * log, const char * str )
{
	if( !log || !str ) 
		return;

	FILE ** cur = log->list;
	FILE ** end = cur + log->count;

	for( ; cur < end; cur++ )
		fwrite(str, strlen(str), sizeof(char), *cur);
}
