#include "texture_widget.hpp"

#include <algorithm>

namespace game::util::imgui
{
  bool texture_widget(const char* id, const resource::Texture* texture, bool isMissing, const ImVec2& maxSize)
  {
    ImGui::PushID(id);
    auto size = maxSize;
    auto isValid = texture && texture->is_valid() && texture->size.x > 0 && texture->size.y > 0;
    if (isValid)
    {
      auto scale = std::min(maxSize.x / (float)texture->size.x, maxSize.y / (float)texture->size.y);
      size = ImVec2(texture->size.x * scale, texture->size.y * scale);
      ImGui::Image(texture->id, size);
    }
    else
    {
      ImGui::Button(isMissing ? "X" : "X", size);
    }

    auto clicked = ImGui::IsItemClicked();
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal) && isValid)
    {
      ImGui::BeginTooltip();
      ImGui::Image(texture->id, ImVec2((float)texture->size.x, (float)texture->size.y));
      ImGui::EndTooltip();
    }
    ImGui::PopID();
    return clicked;
  }
}
