#include "stdafx.h"
#include "grt_logger.h"


Grt_logger * Grt_logger::default_instance()
{
  static Grt_logger logger;
  return &logger;
}


void Grt_logger::do_push_info(const std::string &text)
{
  if (_callbacks_enabled && _task_msg_cb)
    _task_msg_cb(grt::InfoMsg, text);
  else if (_grtm)
    _grtm->get_grt()->send_info(text);
  else
    Logger::push_info(text);
}


void Grt_logger::do_push_warn(const std::string &text)
{
  if (_callbacks_enabled && _task_msg_cb)
    _task_msg_cb(grt::WarningMsg, text);
  else if (_grtm)
    _grtm->get_grt()->send_warning(_(text));
  else
    Logger::push_warn(text);
}


void Grt_logger::do_push_err(const std::string &text)
{
  if (_callbacks_enabled && _task_msg_cb)
    _task_msg_cb(grt::ErrorMsg, text);
  else if (_grtm)
    _grtm->get_grt()->send_error(_(text));
  else
    Logger::push_err(text);
}


int Grt_logger::process_download_progress(double dltotal, double dlnow)
{
  if (!enabled())
    return 0;

  float progress_state= 0.f;
  
  if (dltotal == dlnow)
  {
    if (0 != dltotal)
      progress_state= 1.f;
  }
  else
    progress_state= (float)(dlnow / dltotal);

  std::ostringstream oss;
  oss << (int)(progress_state*100) << "%";

  if (_callbacks_enabled && _task_progress_cb)
    _task_progress_cb(progress_state, _(oss.str().c_str()));
  else
    _grtm->get_grt()->send_progress(progress_state, _(oss.str().c_str()));

  return 0;
}


void Grt_logger::process_task_msg(const grt::Message &msg)
{
  if (!enabled())
    return;
  
  switch (msg.type)
  {
  case grt::WarningMsg:
  case grt::ErrorMsg:
  case grt::InfoMsg:
    _task_msg_cb(msg.type, msg.text);
    break;
  case grt::OutputMsg:
    Logger::push_info(msg.text);
    break;
  case grt::ProgressMsg:
    _task_progress_cb(msg.progress, msg.text);
    break;
  }
}


void Grt_logger::process_task_fail(const std::exception &error)
{
  if (!enabled())
    return;

  _task_fail_cb(error.what());
}


void Grt_logger::process_task_finish(grt::ValueRef res)
{
  if (!enabled())
    return;

  _grtm->get_grt()->send_info(grt::StringRef::cast_from(res));
  _grtm->perform_idle_tasks();
  _task_finish_cb();
}
