# Common helpers for building CosmicSDK examples.
include_guard(GLOBAL)

# Accept library path as an argument.
set(LIBRARY_PATH "" CACHE PATH "Path to the static library")

# Accept include path as an argument.
set(INCLUDE_PATH "" CACHE PATH "Path to the include directory")

# Set library prefixes and suffixes for Windows.
if(WIN32)
	set(CMAKE_SHARED_LIBRARY_PREFIX "")
	set(CMAKE_IMPORT_LIBRARY_PREFIX "")
	set(CMAKE_STATIC_LIBRARY_PREFIX "")
	set(CMAKE_SHARED_LIBRARY_SUFFIX ".dll")
	set(CMAKE_IMPORT_LIBRARY_SUFFIX ".lib")
	set(CMAKE_STATIC_LIBRARY_SUFFIX ".lib")
endif()

include(FetchContent)

# Import hidapi.
FetchContent_Declare(
	hidapi
	GIT_REPOSITORY https://github.com/libusb/hidapi.git
	GIT_TAG        hidapi-0.14.0
)
FetchContent_MakeAvailable(hidapi)

# Create an alias target 'hidapi' based on the platform-specific backend in case it doesn't already exist.
if(NOT TARGET hidapi)
    if(APPLE)
        if(TARGET hidapi_darwin)
            add_library(hidapi ALIAS hidapi_darwin)
        else()
            message(FATAL_ERROR "No suitable HIDAPI target found for macOS.")
        endif()
    elseif(UNIX)
        if(TARGET hidapi_libusb)
            add_library(hidapi ALIAS hidapi_libusb)
        elseif(TARGET hidapi_hidraw)
            add_library(hidapi ALIAS hidapi_hidraw)
        else()
            message(FATAL_ERROR "No suitable HIDAPI target found for Linux.")
        endif()
    elseif(WIN32)
        if(TARGET hidapi_winapi)
            add_library(hidapi ALIAS hidapi_winapi)
        else()
            message(FATAL_ERROR "No suitable HIDAPI target found for Windows.")
        endif()
    else()
        message(FATAL_ERROR "Unsupported platform: no HIDAPI backend.")
    endif()
endif()

function(cosmic_add_c_example target src link_static)
	add_executable(${target} ${src})

	target_include_directories(${target} PUBLIC
		${INCLUDE_PATH}
		${hidapi_SOURCE_DIR}/hidapi
	)

	target_link_directories(${target} PUBLIC
		${LIBRARY_PATH}
	)

	if(MSVC)
		set(common_libs hidapi)
	elseif(APPLE)
		set(common_libs hidapi c++)
	else()
		set(common_libs hidapi stdc++)
	endif()

	if(link_static)
		set(sdk_lib cosmicsdk_static)
	else()
		set(sdk_lib cosmicsdk)
	endif()

	target_link_libraries(${target}
		${sdk_lib}
		${common_libs}
		$<$<BOOL:${MSVC}>:legacy_stdio_definitions>
	)
endfunction()

function(cosmic_add_cpp_example target src link_static)
	add_executable(${target} ${src})

	target_include_directories(${target} PUBLIC
		${INCLUDE_PATH}
		${hidapi_SOURCE_DIR}/hidapi
	)

	target_link_directories(${target} PUBLIC
		${LIBRARY_PATH}
	)

	if(link_static)
		set(sdk_lib cosmicsdk_static)
	else()
		set(sdk_lib cosmicsdk)
	endif()

	target_link_libraries(${target}
		${sdk_lib}
		hidapi
	)
endfunction()
