cmake_minimum_required(VERSION 3.16)
project(wtops_cpp VERSION 1.1.0 LANGUAGES CXX)
find_package(CURL 7.62 REQUIRED)
find_package(nlohmann_json 3.12 QUIET CONFIG)
if(NOT nlohmann_json_FOUND)
  include(FetchContent)
  set(JSON_BuildTests OFF CACHE BOOL "" FORCE)
  FetchContent_Declare(nlohmann_json
    URL https://github.com/nlohmann/json/releases/download/v3.12.0/json.tar.xz
    URL_HASH SHA256=42f6e95cad6ec532fd372391373363b62a14af6d771056dbfc86160e6dfff7aa)
  if(POLICY CMP0135)
    cmake_policy(SET CMP0135 NEW)
  endif()
  FetchContent_MakeAvailable(nlohmann_json)
endif()
add_library(wtops_client INTERFACE)
add_library(wtops::client ALIAS wtops_client)
target_compile_features(wtops_client INTERFACE cxx_std_17)
target_include_directories(wtops_client INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(wtops_client INTERFACE CURL::libcurl nlohmann_json::nlohmann_json)
# FindCURL on older CMake does not propagate the dependencies of static libcurl.
# pkg-config supplements them on Unix; vcpkg's CURL target already supplies them.
if(UNIX)
  find_package(PkgConfig QUIET)
  if(PkgConfig_FOUND)
    pkg_check_modules(CURL_PC QUIET IMPORTED_TARGET libcurl)
    if(TARGET PkgConfig::CURL_PC)
      target_link_libraries(wtops_client INTERFACE PkgConfig::CURL_PC)
      if("${CURL_LIBRARIES}" MATCHES "\\.a($|;)")
        target_link_directories(wtops_client INTERFACE ${CURL_PC_STATIC_LIBRARY_DIRS})
        target_link_libraries(wtops_client INTERFACE ${CURL_PC_STATIC_LIBRARIES})
        target_link_options(wtops_client INTERFACE ${CURL_PC_STATIC_LDFLAGS_OTHER})
      endif()
    endif()
  endif()
endif()
option(WTOPS_BUILD_EXAMPLE "Build runnable example" ON)
option(WTOPS_BUILD_TESTS "Build offline client tests" OFF)
if(WTOPS_BUILD_EXAMPLE)
  add_executable(wtops-example example.cpp)
  target_link_libraries(wtops-example PRIVATE wtops::client)
endif()
if(WTOPS_BUILD_TESTS)
  enable_testing()
  find_package(Python3 REQUIRED COMPONENTS Interpreter)
  add_executable(wtops_tests tests/client_tests.cpp)
  target_link_libraries(wtops_tests PRIVATE wtops::client)
  if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
    target_compile_options(wtops_tests PRIVATE -Wall -Wextra -Wpedantic -Werror)
  endif()
  add_test(NAME wtops_cpp_offline COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_tests.py $<TARGET_FILE:wtops_tests>)
  set_tests_properties(wtops_cpp_offline PROPERTIES TIMEOUT 45)
endif()
