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

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>

#include "app.hh"
#include "input.hh"


namespace pg {
namespace {

class Exporter final : public App {
 public:
  static inline TypeInfo kType = TypeInfo::Create<Exporter>("Exporter");

  Exporter() noexcept {
  }

  void Update() noexcept override {
    const auto id = " Exporter | "+
        std::to_string(reinterpret_cast<uintptr_t>(this));

    if (ImGui::Begin(id.c_str())) {
      ImGui::DragInt("src", &src_);
      ImGui::InputText("dir", &dir_);
      if (ImGui::Button("export")) {
        Export();
      }
    }
    ImGui::End();
  }

 private:
  int src_ = 0;
  std::string dir_;

  void Export() noexcept {
    const auto src =
        Input::instance().slots(static_cast<size_t>(src_));

    const auto n = src->frames();
    for (size_t i = 0; i < n; ++i) {
      const auto f = src->Fetch(i);
      if (!f.rgba) break;

      const auto path = dir_+"/"+std::to_string(i)+".png";
      stbi_write_png(
          path.c_str(),
          static_cast<int>(f.w), static_cast<int>(f.h), 4,
          f.rgba, static_cast<int>(f.w*4));
    }
  }
};

}
}  // namespace pg