find_package(Python3 COMPONENTS Interpreter Development)

# Handle where to install the resulting Python package
if(CALL_FROM_SETUP_PY)
  # The CMakeExtension will set CMAKE_INSTALL_PREFIX to the root
  # of the resulting wheel archive
  set(POCKETSPHINX_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX})
else()
  message(FATAL_ERROR
    "Please do not try to build the Python module outside of setup.py")
endif()

# Set the Python module name (.py file) properly
set_property(SOURCE ../pocketsphinx.i PROPERTY SWIG_MODULE_NAME bindings)
# SWIG-ify and compile the bindings
swig_add_library(bindings
  TYPE MODULE
  LANGUAGE python
  OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/pocketsphinx5
  OUTFILE_DIR ${CMAKE_CURRENT_BINARY_DIR}
  SOURCES
  ../pocketsphinx.i
  )
# Link the bindings with pocketsphinx and Python
target_link_libraries(bindings PRIVATE pocketsphinx Python3::Python)
# Build the library in the proper place and not the weird random CMake place
set_target_properties(bindings PROPERTIES
  LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/pocketsphinx5)
# This does something, not sure what
set_property(TARGET bindings PROPERTY SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE)
# Enable parsing the doxygen comments (FIXME: does this work?)
set_property(TARGET bindings PROPERTY SWIG_COMPILE_OPTIONS -doxygen)

# Installation stuff
# Get the autogenerated Python file
get_property(WRAPPER_PY_FILE
  TARGET bindings
  PROPERTY SWIG_SUPPORT_FILES)
# Install the autogenerated Python file
install(
  FILES ${WRAPPER_PY_FILE}
  DESTINATION ${POCKETSPHINX_INSTALL_PREFIX}
  COMPONENT bindings)
# Install the __init__ply file
install(
  FILES __init__.py
  DESTINATION ${POCKETSPHINX_INSTALL_PREFIX})
# Install the SWIG library
install(
  TARGETS bindings
  COMPONENT bindings
  LIBRARY DESTINATION ${POCKETSPHINX_INSTALL_PREFIX}
  ARCHIVE DESTINATION ${POCKETSPHINX_INSTALL_PREFIX}
  RUNTIME DESTINATION ${POCKETSPHINX_INSTALL_PREFIX})
