#include "input.hh"

#include <imgui.h>
#include <imgui_stdlib.h>


namespace pg {

Input Input::instance_;


size_t Input::Add(Data* data) noexcept {
  slots_.push_back(data);
  return slots_.size()-1;
}

void Input::Update() noexcept {
  if (ImGui::BeginMainMenuBar()) {
    if (ImGui::BeginMenu("Input")) {
      for (size_t i = 0; i < slots_.size(); ++i) {
        const auto str =
            std::to_string(i)+". "+slots_[i]->name();
        ImGui::MenuItem(str.c_str());
      }
      ImGui::EndMenu();
    }
    ImGui::EndMainMenuBar();
  }
}


std::vector<float> Input::Data::FetchSamples(
    size_t st, size_t dur, float xf, float yf, size_t offset) noexcept {
  std::vector<float> ret(dur);
  for (size_t i = 0; i < dur; ++i) {
    const auto frame = Fetch(i+st);
    if (!frame.rgba) continue;

    const auto fwf = static_cast<float>(frame.w);
    const auto fhf = static_cast<float>(frame.h);
    const auto fhi = static_cast<intmax_t>(frame.h);

    const auto x = static_cast<intmax_t>(xf*fwf);
    const auto y = static_cast<intmax_t>(yf*fhf);

    const auto v = frame.rgba + 4*(y*fhi+x);
    ret[i] = static_cast<float>(v[offset]) / UINT8_MAX;
  }
  return ret;
}

}  // namespace pg