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

#include <utility/helper_functions.hpp>
#include "output/detail/SoundBoardPinController.h"

#include "utility/config.h"

namespace flippR_driver
{
namespace output
{
namespace detail
{

SoundBoardPinController::SoundBoardPinController(std::shared_ptr<std::mutex> output_item_mutex,
                                                 uint8_t fire_address,
                                                 const std::array<uint8_t, 7> address_pins) :
  output_item_mutex{output_item_mutex},
  fire_address{fire_address},
  address_pins(address_pins)
{
  CLOG(DEBUG, OUTPUT_LOGGER) << "Created SoundBoardPinController";
}


SoundBoardPinController::SoundBoardPinController(std::shared_ptr<std::mutex> output_item_mutex) :
  output_item_mutex{output_item_mutex}
{
  CLOG(DEBUG, OUTPUT_LOGGER) << "Created SoundBoardPinController without addresses!";
}

void SoundBoardPinController::activate(const items::detail::Sound &sound)
{
  std::lock_guard<std::mutex> guard(*output_item_mutex);

  write_sound_address(sound.get_address());

  fire_sound();
}

void SoundBoardPinController::deactivate(const items::detail::Sound &sound)
{
  std::lock_guard<std::mutex> guard(*output_item_mutex);

  write_sound_address(0);

  fire_sound();
}


void SoundBoardPinController::write_sound_address(const uint8_t &address) const
{
    write_pin(this->address_pins[0], address & 0b0000001u);
    write_pin(this->address_pins[1], address & 0b0000010u);
    write_pin(this->address_pins[2], address & 0b0000100u);
    write_pin(this->address_pins[3], address & 0b0001000u);
    write_pin(this->address_pins[4], address & 0b0010000u);
    write_pin(this->address_pins[5], address & 0b0100000u);
    write_pin(this->address_pins[6], address & 0b1000000u);
}

void SoundBoardPinController::fire_sound() const
{
    PinController::write_pin(this->fire_address, true);
    PinController::write_pin(this->fire_address, false);
}

void SoundBoardPinController::write_pin(const uint8_t &pin, const bool &value) const
{
    PinController::write_pin(pin, value);
}

void SoundBoardPinController::set_address_pins(std::array<uint8_t, 7> address_pins)
{
  this->address_pins = address_pins;

  for(auto & pin : address_pins)
  {
    this->initialize_output_pin(pin);
  }

  CLOG(DEBUG, OUTPUT_LOGGER) << "Pin addresses for sounds set to: " + help::make_list_string<std::array<uint8_t, 7>>(address_pins);
}

void SoundBoardPinController::set_fire_address(const uint8_t &fire_address)
{
  this->fire_address = fire_address;
  CLOG(DEBUG, OUTPUT_LOGGER) << "Fire-pin address for sounds set to: " << int{fire_address};
}

}
}
}
