#pragma once

#ifndef LOGGER_H_
#define LOGGER_H_

#include <io.h>   // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().
#include <iostream>

#define LOG_MAX 1 * 1024 * 1024

inline bool IsLogsDirectory() {
	if ( access( "logs", 0 ) == 0 )
	{
		struct stat status;
		stat( "logs", &status );

		if ( status.st_mode & S_IFDIR )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

inline int GetFileSize(char* filename) {
	struct stat status;
	stat( filename, &status );

	if (status.st_size > 0) {
		return status.st_size;
	} else {
		return 0;
	}
}

inline void Logger(char* filename, char* text) {
	// make sure the filename is valid
	if (filename != NULL) {
		// prepend the logs directory to the filename
		char fn[64];
		sprintf(fn, "logs\\%s", filename);

		// make sure the logs directory exists
		if (!IsLogsDirectory()) return;

		// get the filesize
		int filesize = GetFileSize(fn);
		// if the filesize will be greater than our limit then rename to back file
		if ((filesize + strlen(text) + 17) >= LOG_MAX) {
			// create the file with the .bak extension
			char newname[64];
			sprintf(newname, "%s.bak", fn);
			// remove the old bak file
			int result = remove( newname );
			// rename the file as .bak
			result = rename( fn, newname );
		}

		// create the timestamp
		char timestamp[32];
		SYSTEMTIME lt;
		GetLocalTime(&lt);
		sprintf(timestamp, "%02d:%02d:%02d.%03d", lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);

		// try to open the file.  we will try a bunch of times.
		int tries = 100;
		FILE* file = NULL;
		while (file == NULL) {
			file = fopen(fn, "a");
			if (file != NULL) break;

			if (--tries == 0) {
				return;
			} else {
				Sleep(10);
			}
		}

		// log to file
		fprintf(file, "%s   %s\r\n", timestamp, text);
		fclose(file);
	}

#if DEBUG
	std::cout << text << std::endl;
#endif
}

#endif