#!
#! @ingroup group_sdk_cmake
#!
#! macro gather_headers_and_sources find all headers, sources, including the qt ui, moc and resources
#! and create two variables from it: ${Name}_HEADERS ${Name}_SOURCES, and define all needed commands for qt
#! if BaseDirectory is specified, the glob recurse starts in directory DIR
#!
#! Usage:
#! \code
#! gather_headers_and_sources(Name [BaseDirectory])
#! \endcode
#!
#! \param Name (required)          the prefix of the resulting variables ${Name}_HEADERS ${Name}_SOURCES
#! \param BaseDirectory (optional) do not start gathering from current subdirectory but from the given directory
macro(gather_headers_and_sources Name)
  # gather all possible C++ and Qt sources
  if (${ARGC} EQUAL 1)
    file(GLOB_RECURSE HEADERS *.h)
    file(GLOB_RECURSE SRCS *.cpp *.c)
    file(GLOB_RECURSE File_UI *.ui)
    file(GLOB_RECURSE File_QRC *.qrc)
  else()
    # if an optional parameter is used, gather everything from BaseDirectory
    file(GLOB_RECURSE HEADERS ${ARGV1}/*.h )
    file(GLOB_RECURSE SRCS ${ARGV1}/*.cpp *.c)
    file(GLOB_RECURSE File_UI ${ARGV1}/*.ui )
    file(GLOB_RECURSE File_QRC ${ARGV1}/*.qrc )
  endif()

  # remove compiler test files (needed for "detached"/independent extension,
  # i.e., extensions that are not inside a CEP directory structure, but on their own)
  list(FILTER HEADERS EXCLUDE REGEX ".*CompilerIdCXX/.*")
  list(FILTER SRCS EXCLUDE REGEX ".*CompilerIdCXX/.*")
  list(FILTER HEADERS EXCLUDE REGEX ".*CompilerIdC/.*")
  list(FILTER SRCS EXCLUDE REGEX ".*CompilerIdC/.*")

  # remove the testing directory
  list(FILTER HEADERS EXCLUDE REGEX ".*/testing/.*")
  list(FILTER SRCS EXCLUDE REGEX ".*/testing/.*")
  list(FILTER File_UI EXCLUDE REGEX ".*/testing/.*")
  list(FILTER File_QRC EXCLUDE REGEX ".*/testing/.*")

  # manage Qt ui
  qt_wrap_ui (UI ${File_UI})
  
  # manage Qt resources
  qt_add_resources(QRC ${File_QRC})

  # find Q_OBJECT derived class
  foreach(HEADER ${HEADERS})
    file(READ ${HEADER} stream)
    if(stream MATCHES "Q_OBJECT")
      set(MOC_SOURCES ${MOC_SOURCES} ${HEADER})
    endif(stream MATCHES "Q_OBJECT")
  endforeach(HEADER)
  
  # On Windows, Visual Studio, organize files in subdirectories
  if(MSVC)
    source_group("Header Files\\UI Files" FILES ${UI})
    source_group("Source Files\\Moc Files" REGULAR_EXPRESSION "^moc_.*")
    source_group("Source Files\\CLI Files" REGULAR_EXPRESSION "^CommandLineOptions.*")
    source_group("Source Files\\Resources Files" REGULAR_EXPRESSION "^qrc_.*")
    source_group("Source Files\\Resources Files" REGULAR_EXPRESSION ".*\\.qrc$")
    source_group("UI Files" FILES ${File_UI})
  endif()

  # name all headers
  set (${Name}_HEADERS
      ${HEADERS}
      ${UI}
      ${QRC}
  )

  # name all sources
  set (${Name}_SOURCES
      ${HEADERS}
      ${UI}
      ${QRC}
      ${SRCS}
      ${QT_SRCS}
  )
endmacro()
