include(Utils)

if (NOT IOS)
    Find_Package(libjpeg-turbo QUIET)
endif()
if (libjpeg-turbo_FOUND)
    message("Using system libjpeg-turbo")
elseif (NOT IOS)
    file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/deps_ljt)
    execute_process(
            COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${TOOLCHAIN} -DPLATFORM=${PLATFORM} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DLIBJPEGTURBO_REPO=${LIBJPEGTURBO_REPO}
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/deps_ljt
    )
    execute_process(
            COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}/deps_ljt --config Release
            RESULT_VARIABLE build_result
    )
    if (NOT ${build_result} EQUAL "0")
        message(FATAL_ERROR "Failed to build libjpeg-turbo!")
    endif()

    set(libjpeg-turbo_BUILT "built libjpeg-turbo" CACHE INTERNAL ON)
endif ()


function(LinkLibJpegTurbo TARGET)
    if (IOS)
        target_link_libraries(${TARGET} PRIVATE "/opt/libjpeg-turbo-ios/lib/libturbojpeg.a")
        target_include_directories(${TARGET} PRIVATE "/opt/libjpeg-turbo-ios/include")
        return()
    endif ()
    if (libjpeg-turbo_BUILT)
        FindCmakeConfigDirs("${CMAKE_BINARY_DIR}/deps_ljt/INSTALL/" CMAKE_PREFIX_PATH)
    endif()
    find_package(libjpeg-turbo REQUIRED)
    message("libjpeg-turbo was found in: ${libjpeg-turbo_DIR}")
    if (TARGET libjpeg-turbo::turbojpeg-static)
        target_link_libraries(${TARGET} PUBLIC libjpeg-turbo::turbojpeg-static)
        message("Linking static libjpeg-turbo")
    elseif (TARGET libjpeg-turbo::turbojpeg)
        target_link_libraries(${TARGET} PUBLIC libjpeg-turbo::turbojpeg)
        message("Linking shared libjpeg-turbo")
    else ()
        message(FATAL_ERROR "Neither static nor shared libjpeg-turbo exists")
    endif ()
endfunction()
