# Detect NDK Root based on the location of CMAKE_TOOLCHAIN_FILE
function(detect_ndk_root out_var)
  if(CMAKE_TOOLCHAIN_FILE)
    get_filename_component(_dir "${CMAKE_TOOLCHAIN_FILE}" DIRECTORY)
    get_filename_component(_dir "${_dir}" DIRECTORY)
    get_filename_component(_dir "${_dir}" DIRECTORY)
    set(${out_var} "${_dir}" PARENT_SCOPE)
  elseif(DEFINED ENV{ANDROID_NDK})
    set(${out_var} "$ENV{ANDROID_NDK}" PARENT_SCOPE)
  else()
    message(FATAL_ERROR "Could not detect NDK root.")
  endif()
endfunction()

# Detect host platform (darwin-x86_64, linux-x86_64) for NDK prebuilt tools
function(detect_ndk_host_platform out_var)
  if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
    set(${out_var} "darwin-x86_64" PARENT_SCOPE)
  elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
    set(${out_var} "linux-x86_64" PARENT_SCOPE)
  else()
    set(${out_var} "windows-x86_64" PARENT_SCOPE)
  endif()
endfunction()

# Extract numeric API level from ANDROID_PLATFORM
function(get_android_api_level out_var)
  if(ANDROID_PLATFORM MATCHES "android-([0-9]+)")
    set(${out_var} "${CMAKE_MATCH_1}" PARENT_SCOPE)
  elseif(ANDROID_PLATFORM)
    set(${out_var} "${ANDROID_PLATFORM}" PARENT_SCOPE)
  else()
    set(${out_var} "23" PARENT_SCOPE)
  endif()
endfunction()
