/* Copyright 2024 INAF - Osservatorio Astronomico di Cagliari

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

/*! \file logging.cpp
 *
 * \brief Implementation of the logging system.
 */
#include <cstdio>
#include <string>

#ifndef INCLUDE_LOGGING_H_
#include "../include/logging.h"
#endif

using namespace std;

Logger::Logger(int threshold, FILE *logging_output, FILE *error_output) {
  last_message = new string("");
  log_threshold = threshold;
  log_output = logging_output;
  err_output = error_output;
  repetitions = 0;
}

Logger::~Logger() {
  delete last_message;
}

void Logger::err(const std::string& message) {
  fprintf(err_output, "%s", message.c_str());
  fflush(err_output);
}

void Logger::flush(int level) {
  string summary = "\"" + *last_message + "\" issued " + to_string(repetitions);
  if (repetitions == 1) summary += " time.\n";
  else summary += " times.\n";
  if (level == LOG_ERRO) err(summary);
  else {
    if (level >= log_threshold) {
      fprintf(log_output, "%s", summary.c_str());
      fflush(log_output);
    }
  }
  delete last_message;
  last_message = new string("");
  repetitions = 0;
}

void Logger::log(const std::string& message, int level) {
  if (level == LOG_ERRO) err(message);
  else {
    if (level >= log_threshold) {
      fprintf(log_output, "%s", message.c_str());
      fflush(log_output);
    }
  }
}

void Logger::push(const std::string& message) {
  if (repetitions > 0) {
    if (message.compare(*last_message) != 0) {
      flush(LOG_DEBG);
    }
  }
  log(message, LOG_DEBG);
  delete last_message;
  last_message = new string(message);
  repetitions++;
}
