#[[

Create imported targets:
  * QGLEngine::Core
  * QGLEngine::Widgets

These targets include directories and dependencies

]]

cmake_policy(SET CMP0011 NEW) # don`t affect includer policies
cmake_policy(SET CMP0020 NEW) # Automatically link Qt executables to qtmain target on Windows

find_package(PIP REQUIRED)
find_package(QAD REQUIRED)
include(QtWraps)
include(SHSTKMacros)

shstk_is_parent_exists(hasParent PARENT_DIRECTORY)

shstk_set_find_dirs(QGLEngine)

if (NOT BUILDING_QGLEngine)
	shstk_find_header(QGLEngine "qglengine_version.h" ${QGLEngine_INCDIR})
endif()

if(QGLEngine_FIND_VERSION VERSION_GREATER QGLEngine_VERSION)
	message(FATAL_ERROR "QGLEngine version ${QGLEngine_VERSION} is available, but ${QGLEngine_FIND_VERSION} requested!")
endif()

set(__libs "core;widgets")

set(__module_core    Core   )
set(__module_widgets Widgets)

foreach (_l ${__libs})
	set( __inc_${_l} "")
	set(__deps_${_l} "")
	set(__libs_${_l} "")
endforeach()

set(__deps_core    "QAD::Widgets;QAD::PIQtUtils")
set(__deps_widgets "QGLEngine::Core")

#message("find QGLEngine ${BUILDING_QGLEngine}")

if (BUILDING_QGLEngine)

	if (NOT SET_TARGETS_QGLEngine)
		set(SET_TARGETS_QGLEngine ON CACHE BOOL "")
		#message("create aliases")
		foreach(_l ${__libs})
			foreach(_v ${_QT_VERSIONS_})
				set(_m ${__module_${_l}})
				if((NOT TARGET QGLEngine::${_m}${_v}) AND TARGET qglengine_${_l}${_v})
					#message("alias QGLEngine::${_m}${_v} = qglengine_${_l}${_v}")
					set(MULTILIB_QGLEngine__${_m}_SUFFIX_Qt${_v} ${_v} CACHE STRING "")
					add_library(QGLEngine::${_m}${_v} ALIAS qglengine_${_l}${_v})
				endif()
			endforeach()
			list(APPEND QT_MULTILIB_LIST QGLEngine::${_m})
		endforeach()
	endif()
	
	set(QGLENGINE_FOUND ON CACHE BOOL "")

else()

	#message("create interfaces")
	foreach(_l ${__libs})
		foreach(_v ${_QT_VERSIONS_})
			set(_m ${__module_${_l}})
			find_library(QGLENGINE_LIBRARY_${_l}${_v} qglengine_${_l}${_v} HINTS ${QGLEngine_LIBDIR})
			#message("found ${_l}${_v} = ${QGLENGINE_LIBRARY_${_l}${_v}} (${qglengine_INCLUDES})")
			if((NOT TARGET QGLEngine::${_m}${_v}) AND QGLENGINE_LIBRARY_${_l}${_v})
				#message("imported QGLEngine::${_m}${_v} = ${QGLENGINE_LIBRARY_${_l}${_v}}")
				set(MULTILIB_QGLEngine__${_m}_SUFFIX_Qt${_v} ${_v} CACHE STRING "")
				add_library(QGLEngine::${_m}${_v} UNKNOWN IMPORTED)
				set(_deps)
				foreach (_d ${__deps_${_l}})
					if ((${_d} MATCHES "QAD::.*") OR (${_d} MATCHES "QGLEngine::.*"))
						list(APPEND _deps ${_d}${_v})
					else()
						list(APPEND _deps ${_d})
					endif()
				endforeach()
				set_target_properties(QGLEngine::${_m}${_v} PROPERTIES
					IMPORTED_LOCATION "${QGLENGINE_LIBRARY_${_l}${_v}}"
					INTERFACE_INCLUDE_DIRECTORIES "${QGLEngine_INCLUDES}"
					INTERFACE_LINK_LIBRARIES "${_deps}")
			endif()
		endforeach()
		list(APPEND QT_MULTILIB_LIST QGLEngine::${_m})
	endforeach()

endif()

if(hasParent)
	set(QT_MULTILIB_LIST ${QT_MULTILIB_LIST} PARENT_SCOPE)
endif()

set(QGLENGINE_FOUND ON CACHE BOOL "")
