/*
 * DisplayController.cpp
 *
 *  Created on: Aug 7, 2018
 *      Author: Andreas Schneider, Johannes Wendel, Jonas Zeunert
 */

#include "output/detail/DisplayController.h"

#include "output/DisplayController.h"

#include "utility/config.h"

namespace flippR_driver
{
namespace output
{
namespace detail
{

DisplayController::DisplayController(std::map<std::string, std::shared_ptr<items::Display>> & displays,
                                     std::shared_ptr<DisplayBoardPinController> pin_controller
)
  : pin_controller{pin_controller}, is_running(true)
{
  for (auto display : displays)
  {
    this->displays.push_back(std::dynamic_pointer_cast<items::OutputDisplay>(display.second));
  }

  for(auto &display : this->displays) {
    pin_controller->initDisplay(*display);
  }

  activate_displays();

  this->display_cycle_thread = std::thread(&DisplayController::cycle_displays, this);

  CLOG(DEBUG, OUTPUT_LOGGER) << "Created DisplayController and started cycling them.";
}

DisplayController::~DisplayController()
{
  this->is_running = false;

  this->display_cycle_thread.join();
}

void DisplayController::cycle_displays() const
{
  while (is_running)
  {
    //std::this_thread::sleep_for(update_frequency);
    for (auto &display : this->displays)
    {
      pin_controller->write_display(*display);
    }
  }
}

void DisplayController::activate_displays() const
{
  pin_controller->activate_displays();
  CLOG(DEBUG, OUTPUT_LOGGER) << "Activated all displays!";
}

void DisplayController::deactivate_displays() const
{
  pin_controller->deactivate_displays();
  CLOG(DEBUG, OUTPUT_LOGGER) << "Deactivated all displays!";
}

}
}
}
