#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <SDL.h>

#include "Log.h"

FILE* _logFile = NULL;
Uint8 _logFileReady = 0;

#define _DEBUG_BUFFER_SIZE 512
static char _debugBuffer[_DEBUG_BUFFER_SIZE];


void log_start() {
	log_destroy();

    const Uint16 maxFilename = 256;
    char* filename = (char*)malloc(maxFilename * sizeof(char));
    if (!filename) {
        SDL_Log("Could not allocate memory for log file name");
        return;
    }

    CreateDirectoryA("logs", NULL);
    
    SYSTEMTIME time;
    GetSystemTime(&time);
    sprintf_s(filename, maxFilename-10, "logs\\zxian_%04d-%02d-%02d__%02d-%02d-%02d.%03d.txt", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);

    // open the file for writing
    fopen_s(&_logFile, filename, "w");
    if (_logFile == NULL) {
        SDL_Log("Error creating log file %s", filename);
        free(filename);
        return;
    }

    SDL_Log("Opened log file %s\n", filename);
    free(filename);

    fprintf(_logFile, "Opened log file");
    _logFileReady = 1;
}

void log_destroy() {
	if (_logFileReady) {
		fclose(_logFile);
		_logFile = NULL;
	}
    _logFileReady = 0;
}

void log_write(char* string) {
    if (!_logFileReady) {
        return;
    }

    fprintf(_logFile, "\n%s", string);
}

void log_write_char(char ascii) {
    fprintf(_logFile, "%c", ascii);
}

void log_write_string_int(char* string, int intValue1) {
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, string, intValue1);
    log_write(_debugBuffer);
}

void log_write_string_string(char* string, char* string2) {
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, string, string2);
    log_write(_debugBuffer);
}

void log_write_string_string_string(char* string, char* string2, char* string3)
{
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, string, string2, string3);
    log_write(_debugBuffer);
}

void log_write_string_string_string_string(char* string, char* string2, char* string3, char* string4)
{
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, string, string2, string3, string4);
    log_write(_debugBuffer);
}

void log_write_string_double(char* string, double doubleValue1) {
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, string, doubleValue1);
    log_write(_debugBuffer);
}

void log_write_with_timestamp(char* string) {
    SYSTEMTIME time;
    GetSystemTime(&time);
    sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, "[%04d-%02d-%02d %02d:%02d:%02d.%03d] %s", 
        time.wYear, 
        time.wMonth, 
        time.wDay, 
        time.wHour, 
        time.wMinute, 
        time.wSecond, 
        time.wMilliseconds,
        string);

    log_write(_debugBuffer);
}
