#include "logger.hpp"

#include <cstdio>
#include <ctime>
#include <cstdarg>
#include <iostream>

bool restart_gl_log() {
   FILE* file = fopen(GL_LOG_FILE, "w");
   if (!file) {
      cerr << "ERROR: could not open GL_LOG_FILE log file " << GL_LOG_FILE << " for writing" << endl;
      return false;
   }
   time_t now = time(NULL);
   string date(ctime(&now));
   fprintf(file, "GL_LOG_FILE log. local time %s\n", date.c_str());
   fclose(file);
   return true;
}

bool gl_log(const string message, ...) {
   va_list argptr;
   FILE* file = fopen(GL_LOG_FILE, "a");
   if (!file) {
      cerr << "ERROR: could not open GL_LOG_FILE log file " << GL_LOG_FILE << " for appending" << endl;
      return false;
   }
   va_start(argptr, message);
   vfprintf(file, message.c_str(), argptr);
   va_end(argptr);
   fprintf(file, "\n");
   fclose(file);
   return true;
}

bool gl_log_err(const string message, ...) {
   va_list argptr;
   FILE* file = fopen(GL_LOG_FILE, "a");
   if (!file) {
      cerr << "ERROR: could not open GL_LOG_FILE log file " << GL_LOG_FILE << " for appending" << endl;
      return false;
   }
   va_start(argptr, message);
   vfprintf(file, message.c_str(), argptr);
   va_end(argptr);
   fprintf(file, "\n");
   va_start(argptr, message);
   vfprintf(stderr, message.c_str(), argptr);
   va_end(argptr);
   fprintf(stderr, "\n");
   fclose(file);
   return true;
}

ofstream ofs;

void open_log() {
   ofs.open(LOG_FILE, ios::out);

   time_t now = time(NULL);
   string date(ctime(&now));
   ofs << "LOG_FILE log. local time " << date << endl;
}

ofstream& get_log() {
   return ofs;
}

void close_log() {
   ofs.close();
}
