# inspired by google's protobuf cmake module
#  ====================================================================
#
# CAPNP_GENERATE_CPP (public function)
#   SRCS = Variable to define with autogenerated
#          source files
#   HDRS = Variable to define with autogenerated
#          header files
#   ARGN = capnp files
#
#  ====================================================================
function(CAPNP_GENERATE_CPP SRCS HDRS)
  if(NOT ARGN)
    message(SEND_ERROR "Error: CAPNP_GENERATE_CPP() called without any capnp files")
    return()
  endif(NOT ARGN)

  if(CAPNP_GENERATE_CPP_APPEND_PATH)
    # Create an include path for each file specified
    foreach(FIL ${ARGN})
      get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
      get_filename_component(ABS_PATH ${ABS_FIL} PATH)
      list(FIND _capnp_include_path ${ABS_PATH} _contains_already)
      if(${_contains_already} EQUAL -1)
          list(APPEND _capnp_include_path --import-path=${ABS_PATH})
      endif()
    endforeach()
  else()
    set(_capnp_include_path --import-path=${CMAKE_CURRENT_SOURCE_DIR})
  endif()

  set(${SRCS})
  set(${HDRS})
  foreach(FIL ${ARGN})
    get_filename_component(ABS_FIL ${FIL} ABSOLUTE)

    list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL}.c++")
    list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL}.h")

    add_custom_command(
      OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL}.c++"
             "${CMAKE_CURRENT_BINARY_DIR}/${FIL}.h"
      COMMAND  ${CAPNPC_EXECUTABLE}
      ARGS compile --src-prefix=${CMAKE_CURRENT_SOURCE_DIR} --output=${CAPNPC_CXX_EXECUTABLE}:${CMAKE_CURRENT_BINARY_DIR} ${_capnp_include_path} -I${CAPNPC_IMPORT_PATH} ${ABS_FIL}
      DEPENDS ${ABS_FIL}
      COMMENT "Running C++ capnp compiler on ${FIL}"
      VERBATIM )
  endforeach()

  set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE)
  set(${SRCS} ${${SRCS}} CACHE STRING "${SRCS}")
  set(${HDRS} ${${HDRS}} CACHE STRING "${HDRS}")
endfunction()
