# EGL powers the surfaceless headless context the GL tests assert pixels
# against. It is a *test-only* dependency: plot_core never links or includes it,
# so a machine without EGL can still build the library (-DPLOT_BUILD_TESTS=OFF).
# Prefer CMake's own module, fall back to pkg-config, and fail loudly if neither
# can supply EGL rather than silently dropping the GL tests.
find_package(EGL QUIET)
if(NOT EGL_FOUND)
  find_package(PkgConfig QUIET)
  if(PkgConfig_FOUND)
    pkg_check_modules(EGL_PC QUIET IMPORTED_TARGET egl)
  endif()
endif()

if(TARGET EGL::EGL)
  set(plot_egl_library EGL::EGL)
elseif(TARGET PkgConfig::EGL_PC)
  set(plot_egl_library PkgConfig::EGL_PC)
else()
  message(FATAL_ERROR
    "plot: PLOT_BUILD_TESTS=ON requires EGL (EGL/egl.h plus libEGL) for the headless "
    "OpenGL context used by the GL tests. Install it (e.g. libegl-dev, libegl1-mesa-dev "
    "or mesa-libEGL-devel) or configure with -DPLOT_BUILD_TESTS=OFF.")
endif()

find_package(Threads REQUIRED)   # std::thread in the push/read race test

add_executable(plot_tests
  main.cpp
  test_transform.cpp
  test_gl_context.cpp
  test_primitives.cpp
  test_ring_buffer.cpp
  test_minmax_pyramid.cpp
  test_series.cpp
  test_ticks.cpp
  test_measure.cpp
  test_plot.cpp
  test_render_smoke.cpp
  test_controller.cpp
  egl_headless.cpp
)
target_link_libraries(plot_tests PRIVATE plot::core ${plot_egl_library} Threads::Threads)

# The Dear ImGui widget is the one adapter with a test here: its input translation
# (edge synthesis, the hover gate, drag capture, wheel containment) is logic this
# project owns, not a toolkit's. The suite is otherwise ImGui-free, so the source
# and the link are added only when the adapter exists -- which the top-level
# CMakeLists.txt guarantees by adding the adapters before this directory.
if(TARGET plot::imgui)
  target_sources(plot_tests PRIVATE test_imgui_widget.cpp)
  target_link_libraries(plot_tests PRIVATE plot::imgui imgui)
endif()

# The Qt adapter's pointer anchor is deliberately toolkit-free (see
# adapters/qt6/qt_pointer.hpp), so this one piece of that adapter's translation is
# tested without linking Qt -- and without `PLOT_BUILD_QT6`, since no Qt target has
# to exist for it to compile.
target_sources(plot_tests PRIVATE test_qt_pointer.cpp)
target_include_directories(plot_tests PRIVATE "${CMAKE_SOURCE_DIR}/adapters")

# Same switches the library is built with: the cost tests read the counters
# behind them (see include/plot/data/detail/{cover,merge}_count.hpp).
target_compile_definitions(plot_tests PRIVATE PLOT_PYRAMID_COUNT_COVERS
                                             PLOT_PYRAMID_COUNT_MERGES
                                             PLOT_RING_STATS)
plot_apply_warnings(plot_tests)

add_test(NAME plot_tests COMMAND plot_tests)
