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

#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::vector<uint8_t> address_pins) :
  output_item_mutex(output_item_mutex),
  fire_address(fire_address),
  address_pins(address_pins)
{
  CLOG(INFO, OUTPUT_LOGGER) << "Created SoundBoardPinController";
}

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);
    PinController::write_pin(this->fire_address, true);

    PinController::write_pin(this->fire_address, false);
}

}
}
}
