#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>
#include <unistd.h>

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 ( test_memlog ) {
	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 ( "test_log.matrix" ), get_file_size ( ls.c_str() ) );
}

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

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

	dirfilelog L ( "exp/dirfile", 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 ( "dirfile-format.matrix" ) );
	std::string actual ( load_test_file ( "exp/dirfile/format" ) );
	CHECK_EQUAL ( expected, actual );
}
