# -- Python library ---------
# NOTE: when we can use cmake 3.0.14 we can use FindPython
#       to locate NumPy as well, removing the need for the
#       execute_process() call

if (ENABLE_PYTHON)
    find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
    set(Python3_VERSION_XY "${Python3_VERSION_MAJOR}.${Python3_VERSION_MINOR}")

    # find paths by querying python
    execute_process(
        COMMAND "${Python3_EXECUTABLE}" "-c"
        "from distutils import sysconfig; import numpy;
print(sysconfig.get_python_lib(plat_specific=True, prefix=''), end=';');
print(numpy.get_include(), end=';')
"
        RESULT_VARIABLE _Python3_RESULT
        OUTPUT_VARIABLE _Python3_VALUES
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    if (NOT ${Python3_NumPy_RESULT} STREQUAL "0")
        message(FATAL_ERROR "Cannot locate NumPy include dirs")
    endif()
    list(GET _Python3_VALUES 0 Python3_INSTALL_DIR)
    list(GET _Python3_VALUES 1 Python3_NumPy_INCLUDE_DIRS)

    # parse the result

    message(STATUS "Found NumPy include dirs: ${Python3_NumPy_INCLUDE_DIRS}")

    # setup python module
    add_library(PyFr3 MODULE framel.c)
    target_include_directories(
        PyFr3 PRIVATE
        ${Python3_INCLUDE_DIRS}
        ${Python3_NumPy_INCLUDE_DIRS}
        "${CMAKE_SOURCE_DIR}/src"
    )
    set_target_properties(PyFr3 PROPERTIES OUTPUT_NAME framel PREFIX "")

    # use dynamic_lookup on macos
    if (APPLE)
        set_target_properties(PyFr3 PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
    else()
        target_link_libraries(PyFr3 ${Python3_LIBRARIES})
    endif()

    # set extension for windows
    if (WIN32)
        set_target_properties(PyFr3 PROPERTIES SUFFIX ".pyd")
    endif()

    # make sure and build the C library first
    if (NOT DEFINED ENABLE_C OR ENABLE_C)
        add_dependencies(PyFr3 framel)
        target_link_libraries(PyFr3 framel)
    # or link to an existing copy
    else()
        find_library(FRAMEL_LIB framel)
        message(STATUS "Found Frame libraries: ${FRAMEL_LIB}")
        target_link_libraries(PyFr3 ${FRAMEL_LIB})
    endif()

    # install python library
    set(TARGET_SP_DIR "${CMAKE_INSTALL_PREFIX}/${Python3_INSTALL_DIR}")
    install(
        TARGETS PyFr3
        RUNTIME DESTINATION ${TARGET_SP_DIR}
        LIBRARY DESTINATION ${TARGET_SP_DIR}
    )

    # create a egg-info file for pip
    set(EGG_INFO_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-${${PROJECT_NAME}_VERSION}-py${Python3_VERSION_XY}.egg-info")
    file(TOUCH ${EGG_INFO_FILE_NAME})
    install(FILES ${EGG_INFO_FILE_NAME} DESTINATION ${TARGET_SP_DIR})

    # -- setup duplicate python module with old name --
    install(
        FILES ${CMAKE_CURRENT_SOURCE_DIR}/Fr.py
        DESTINATION ${TARGET_SP_DIR}
    )

endif()
