#include "selectable_renamable.hpp"

#include "input_string.hpp"

namespace game::util::imgui
{
  SelectableRenamableResult selectable_renamable(const char* id, std::string& value, const char* fallback,
                                                 bool selected, ImGuiSelectableFlags flags)
  {
    ImGui::PushID(id);

    auto* storage = ImGui::GetStateStorage();
    auto editingID = ImGui::GetID("selectable-renamable-editing");
    auto focusID = ImGui::GetID("selectable-renamable-focus");
    auto isEditing = storage->GetBool(editingID, false);

    SelectableRenamableResult result{.editing = isEditing};
    if (isEditing)
    {
      ImGui::SetNextItemWidth(-FLT_MIN);
      if (storage->GetBool(focusID, false))
      {
        ImGui::SetKeyboardFocusHere();
        storage->SetBool(focusID, false);
      }

      result.renamed = input_string("##rename", value, ImGuiInputTextFlags_EnterReturnsTrue);
      result.editing = true;
      if (ImGui::IsItemDeactivated())
      {
        storage->SetBool(editingID, false);
        result.editing = false;
      }
    }
    else
    {
      auto label = value.empty() ? std::string{fallback ? fallback : ""} : value;
      result.selected = ImGui::Selectable(label.c_str(), selected, flags);
      if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
      {
        storage->SetBool(editingID, true);
        storage->SetBool(focusID, true);
        result.selected = true;
        result.editing = true;
      }
    }

    ImGui::PopID();
    return result;
  }
}
