#include "base/loggers.h"
#include "../test_util.h"
#include "osutils.h"
#include "UnitTest++.h"
#include <string>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef WIN32
#include <unistd.h>
#endif

using namespace bdm;

int get_file_size ( const char *fname ) {
	struct stat st;
	if ( stat ( fname, &st ) ) {
		std::string msg = "can't stat ";
		msg += fname;
		throw std::runtime_error ( msg );
	}

	int sz = static_cast<int> ( st.st_size );
	if ( sz != st.st_size ) {
		std::string msg = fname;
		msg += " too big";
		throw std::runtime_error ( msg );
	}

	return sz;
}

TEST ( memlog_test ) {
	RV th = RV ( "{alog blog }" );
	RV r = RV ( "{r }", "2" );

	string ls ( "test_log.bin" );
	remove_all ( ls.c_str() );

	memlog logger ( 100, ls );

	int rid = logger.add ( r, "" );
	int thid = logger.add ( th, "th" );

	logger.init();

	for ( int i = 0; i < 10; i++ ) {
		logger.logit ( rid, vec_2 ( ( double ) i, ( double ) ( i + 1 ) ) );
		logger.logit ( thid, vec_2 ( ( double ) ( 100 - i ), ( double ) ( i - 50 ) ) );
		logger.step();
	}

	logger.finalize();

	CHECK_EQUAL ( get_file_size ( "logger_test.matrix" ), get_file_size ( ls.c_str() ) );
}

TEST ( dirfilelog_test ) {
	RV th = RV ( "{alog blog }" );
	RV r = RV ( "{r }", "2" );

	string ls ( "exp" );
	remove_all ( ls.c_str() );
	makedir ( ls, false );
	remove_all ( "dirfilelog_files" );

	dirfilelog L ( "dirfilelog_files", 10 );

	int rid = L.add ( r, "" );
	int thid = L.add ( th, "th" );

	L.init();

	for ( int i = 0; i < 150; i++ ) {
		L.logit ( rid, vec_2 ( ( double ) i, ( double ) ( i + 1 ) ) );
		L.logit ( thid, vec_2 ( ( double ) ( 100 - i ), ( double ) ( i - 50 ) ) );
		L.step();
	}

	L.finalize();

	std::string expected ( load_test_file ( "logger_test_dirfile_format.matrix" ) );
	std::string actual ( load_test_file ( "dirfilelog_files/format" ) );
	CHECK_EQUAL ( expected, actual );
}
