/*
 * SoundFactory.cpp
 *
 *  Created on: December 28, 2019
 *      Author: Andreas Schneider, Johannes Wendel, Jonas Zeunert
 */

#include "SoundFactory.h"

namespace  flippR_driver
{
namespace output
{

SoundFactory::SoundFactory(nlohmann::json &object, std::shared_ptr<SoundBoardPinController> pin_controller) :
  ItemFactory{object, pin_controller}
{
  this->set_fire_pin();
  this->set_address_pins();
}

std::map<std::string, std::shared_ptr<items::Sound>> SoundFactory::getItemMap()
{
  auto sounds = this->object.at(config_path::sound_path);
  std::map<std::string, std::shared_ptr<items::Sound>> sound_map;
  for (auto sound : sounds)
  {
    auto name = sound.at(config_path::item_name).get<std::string>();
    auto address = sound.at(config_path::item_address).get<uint8_t >();
    auto id = sound.at(config_path::item_identifier).get<uint>();

    auto sound_item = std::make_shared<items::detail::Sound>(std::static_pointer_cast<SoundBoardPinController>(this->pin_controller), address, name, id);

    sound_map.emplace(name, sound_item);
  }
  return sound_map;
}

void SoundFactory::set_fire_pin()
{
  auto fire_pin = object.at(config_path::fire_pin);
  auto fire_pin_address = fire_pin.at(config_path::item_address).get<uint8_t>();
  if (fire_pin.find(config_path::item_extender) != fire_pin.end())
  {
    auto extender_name = fire_pin.at(config_path::item_extender).get<std::string>();
    fire_pin_address += this->get_extender_pin_base(extender_name);
  }
  std::dynamic_pointer_cast<detail::SoundBoardPinController>(this->pin_controller)->set_fire_address(fire_pin_address);
}

void SoundFactory::set_address_pins()
{
  auto address_pins = object.at(config_path::address_pins);

  std::array<uint8_t, 7> pins;

  for (auto & pin_json : address_pins)
  {
    uint8_t pin = pin_json.at(config_path::item_address).get<uint8_t>();
    if (pin_json.find(config_path::item_extender) != pin_json.end())
    {
      auto extender_name = pin_json.at(config_path::item_extender).get<std::string>();
      pin += this->get_extender_pin_base(extender_name);
    }
    uint8_t id = pin_json.at(config_path::item_identifier).get<uint8_t>();

    pins[id] = pin;
  }

  std::dynamic_pointer_cast<detail::SoundBoardPinController>(this->pin_controller)->set_address_pins(pins);
}

}
}
