//
// Created by rhetenor on 14.12.18.
//

#include "output/detail/DisplayBoardPinController.h"

#include <thread>

#include "utility/config.h"

namespace flippR_driver
{
namespace output
{
namespace detail
{

DisplayBoardPinController::DisplayBoardPinController(std::map<std::string, uint8_t> pins_display) :
  pins_display_board(std::move(pins_display))
{
  initialize_pins_output(0, pins_display.begin(), pins_display.end());

  CLOG(INFO, OUTPUT_LOGGER) << "Created DisplayBoardPinController";
}

void DisplayBoardPinController::activate_displays() const
{
  write_pin(pins_display_board.at("run"), 1);
}

void DisplayBoardPinController::deactivate_displays() const
{
  write_pin(pins_display_board.at("run"), 0);
}

void DisplayBoardPinController::write_display(const items::OutputDisplay &display) const
{
  std::string content = display.get_content();

  for (uint8_t i = 0; i < content.size(); i++)
  {
    write_display_digit(display.get_address(), content.at(i), i);
  }
}


void DisplayBoardPinController::write_display_digit(uint8_t display_address, uint8_t content, uint8_t position) const
{
  select_display_segment(position);

  select_display_digit(content);

  run_display(display_address);

  std::this_thread::sleep_for(std::chrono::milliseconds(DISPLAY_SLEEP_TIME_MILLI));
}

void DisplayBoardPinController::select_display_segment(uint8_t segment) const
{
  write_pin(pins_display_board.at("segment_select_A"), segment & ~0b001u);
  write_pin(pins_display_board.at("segment_select_B"), segment & ~0b010u);
  write_pin(pins_display_board.at("segment_select_C"), segment & ~0b100u);
}

void DisplayBoardPinController::select_display_digit(uint8_t content) const
{
  write_pin(pins_display_board.at("digit_select_A"), content & 0b0001u);
  write_pin(pins_display_board.at("digit_select_B"), content & 0b0010u);
  write_pin(pins_display_board.at("digit_select_C"), content & 0b0100u);
  write_pin(pins_display_board.at("digit_select_D"), content & 0b1000u);
}

void DisplayBoardPinController::run_display(uint8_t address) const
{
  write_pin(pins_display_board.at("display_select_" + std::to_string(address)), 0);

  write_pin(pins_display_board.at("display_select_" + std::to_string(address)), 1);
}

}
}
}