#include "busy_indicator.hpp"

#include "updater.hpp"
#include "graphics.hpp"

BusyIndicator& BusyIndicator::get_instance() 
{
  static BusyIndicator b;
  return b;
}

BusyIndicator::BusyIndicator()
  : status(IDLE), status_overlay("status led"), disabled(false)
{
  conf = Config::get_instance();
  render = Render::get_instance();
  Updater &updater = Updater::get_instance();

  if (conf->p_busy_indicator()) {
    TimeFunctori<BusyIndicator> *time_func = new TimeFunctori<BusyIndicator>(this, &BusyIndicator::check_status);
    TimeFunctorv<BusyIndicator> *call_func = new TimeFunctorv<BusyIndicator>(this, &BusyIndicator::print_status);
    updater.timer.add(TimeElement("status indicator", time_func, call_func));
  }
}

int BusyIndicator::check_status()
{
  return 200; // ms
}

void BusyIndicator::print_status()
{
  if (!disabled) {

    if (status == old_status) // nothing to draw
      return;

    render->image_mut.enterMutex();
    render->device->wait_for_output_done();

    if (status_overlay.elements.size() > 0)
      status_overlay.partial_cleanup();
  
    if (status == IDLE)
      status_overlay.add(new PObj("idle.png", conf->p_v_res()-30, 5, 1, NOSCALING)); 
    else if (status == BUSY)
      status_overlay.add(new PObj("busy.png", conf->p_v_res()-30, 5, 1, NOSCALING)); 
    // FIXME: error?

    old_status = status;

    render->draw("status led", true);
    render->image_mut.leaveMutex();
  }
}

void BusyIndicator::idle()
{
  if (conf->p_busy_indicator())
    status = IDLE;
}

void BusyIndicator::busy()
{
  if (conf->p_busy_indicator()) {
    status = BUSY;
    print_status();
  }
}

void BusyIndicator::busy_no_print()
{
  if (conf->p_busy_indicator())
    status = BUSY;
}

void BusyIndicator::disable()
{
  Updater &updater = Updater::get_instance();
  updater.timer.deactivate("status indicator");
  status_overlay.cleanup();
  disabled = true;
}

void BusyIndicator::enable()
{
  Updater &updater = Updater::get_instance();
  updater.timer.activate("status indicator");
  disabled = false;
}
