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

#include <output/items/Lamp.h>
#include <output/detail/DriverBoardPinController.h>
#include "LampFactory.h"
#include "output/items/detail/Lamp.h"

namespace flippR_driver
{
namespace output
{

LampFactory::LampFactory(nlohmann::json &object, std::shared_ptr<DriverBoardPinController> pin_controller) :
  ItemFactory{object, pin_controller}
{
  this->set_address_pins();
  this->set_mux_pins();

  auto controller = std::dynamic_pointer_cast<detail::DriverBoardPinController>(this->pin_controller);

  auto data_pin = this->get_address_pin(this->object.at(config_path::data_pin));
  controller->set_data_pin(data_pin);

  auto run_pin = this->get_address_pin(this->object.at(config_path::run_pin));
  controller->set_run_pin(run_pin);
}

std::map<std::string, std::shared_ptr<items::Lamp>> LampFactory::getItemMap()
{
  auto lamps = this->object.at(config_path::lamps_path);
  std::map<std::string, std::shared_ptr<items::Lamp>> lamp_map;
  for (auto lamp : lamps)
  {
    auto name = lamp.at(config_path::item_name).get<std::string>();
    auto address = lamp.at(config_path::item_address).get<uint8_t >();

    auto lamp_item = std::make_shared<items::detail::Lamp>(std::static_pointer_cast<DriverBoardPinController>(this->pin_controller), address, name);
    lamp_map.emplace(name, lamp_item);
  }
  return lamp_map;
}

void LampFactory::set_address_pins()
{
  auto address_pins = this->object.at(config_path::address_pins);

  std::array<uint8_t, 3> pins;

  pins.at(0) = this->get_address_pin(address_pins.at("A0"));
  pins.at(1) = this->get_address_pin(address_pins.at("A1"));
  pins.at(2) = this->get_address_pin(address_pins.at("A2"));

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

uint8_t LampFactory::get_address_pin(nlohmann::json & pin_object)
{
  auto address = pin_object.at(config_path::item_address).get<uint8_t>();
  uint8_t pin_base = 0;
  if (pin_object.find(config_path::item_extender) != pin_object.end())
  {
    auto extender = pin_object.at(config_path::item_extender).get<std::string>();
    pin_base = this->get_extender_pin_base(extender);
  }

  return address + pin_base;
}

void LampFactory::set_mux_pins()
{
  auto address_pins = this->object.at(config_path::enable_pins);

  std::array<uint8_t, 13> pins;

  for(char i = 1; i < 14; i++)
  {
    pins.at(i-1) = this->get_address_pin(address_pins.at("E" + std::to_string(i)));
  }

  std::dynamic_pointer_cast<detail::DriverBoardPinController>(this->pin_controller)->set_mux_pins(pins);
}

}
}
