psemek_add_build_tool(psemek-resource-compiler FALSE compiler.cpp)

function(psemek_add_resources_impl MODE TARGET)
	if(PSEMEK_PACKAGE_MODE)
		if(NOT (TARGET ${TARGET}))
			return()
		endif()
	endif()

	target_link_libraries(${TARGET} ${MODE} psemek-rs)

	get_target_property(OUT_DIR ${TARGET} BINARY_DIR)
	get_target_property(INPUT_DIR ${TARGET} SOURCE_DIR)

	target_include_directories(${TARGET} ${MODE} "${OUT_DIR}/resource/include")

	while(ARGN)
		list(GET ARGN 0 FILE)
		list(GET ARGN 1 NAME)
		list(REMOVE_AT ARGN 0 1)

		get_filename_component(NAME_PREFIX ${NAME} DIRECTORY)

		file(MAKE_DIRECTORY "${OUT_DIR}/resource/include/${NAME_PREFIX}")
		file(MAKE_DIRECTORY "${OUT_DIR}/resource/source/${NAME_PREFIX}")

		set(OUT_HEADER "${OUT_DIR}/resource/include/${NAME}.hpp")
		set(OUT_SOURCE "${OUT_DIR}/resource/source/${NAME}.cpp")

		set(_DEPEND_TARGET psemek-resource-compiler)
		if(PSEMEK_PACKAGE_MODE AND (NOT PSEMEK_PACKAGE_HOST))
			set(_DEPEND_TARGET)
		endif()

		add_custom_command(OUTPUT "${OUT_HEADER}" "${OUT_SOURCE}"
			COMMAND psemek-resource-compiler "${FILE}" ${NAME} "${OUT_HEADER}" "${OUT_SOURCE}"
			DEPENDS psemek-resource-compiler "${FILE}"
			WORKING_DIRECTORY "${INPUT_DIR}")

		target_sources(${TARGET} PRIVATE "${FILE}" "${OUT_HEADER}" "${OUT_SOURCE}")
	endwhile()
endfunction()

function(psemek_glob_resources_impl MODE TARGET PATH PREFIX)
	set(RESOURCES_LIST)

	get_filename_component(PATH "${PATH}" ABSOLUTE)

	if(DEFINED ARGV4)
		set(STRIP_EXTENSION ${ARGV4})
	else()
		set(STRIP_EXTENSION OFF)
	endif()

	file(GLOB_RECURSE INPUT_FILES LIST_DIRECTORIES false RELATIVE "${PATH}" "${PATH}/*")

	foreach(INPUT_FILE ${INPUT_FILES})
		set(RESOURCE_FILE "${PATH}/${INPUT_FILE}")
		set(RESOURCE_NAME "${INPUT_FILE}")

		if(STRIP_EXTENSION)
			string(REGEX REPLACE "\\.[^.]*$" "" RESOURCE_NAME "${RESOURCE_NAME}")
		endif()

		string(REPLACE "." "_" RESOURCE_NAME "${RESOURCE_NAME}")
		list(APPEND RESOURCES_LIST "${RESOURCE_FILE}" "${PREFIX}/${RESOURCE_NAME}")
	endforeach()

	psemek_add_resources_impl(${MODE} ${TARGET} ${RESOURCES_LIST})
endfunction()

function(psemek_add_resources)
	psemek_add_resources_impl(PRIVATE ${ARGN})
endfunction()

function(psemek_add_public_resources)
	psemek_add_resources_impl(PUBLIC ${ARGN})
endfunction()

function(psemek_glob_resources)
	psemek_glob_resources_impl(PRIVATE ${ARGN})
endfunction()

function(psemek_glob_public_resources)
	psemek_add_resources_impl(PUBLIC ${ARGN})
endfunction()
