include("${CMAKE_CURRENT_LIST_DIR}/Cpp11EmbedGeneric.cmake")

# Loosely based on this guide
# https://techtinkering.com/2013/02/12/using-dynamically-generated-header-files-with-cmake/

# Linking against this target will ensure that the headers associated with it
# are built and can be used.
function(add_cpp11_embed_target
    TARGET_NAME
)
    add_library(${TARGET_NAME} INTERFACE)
    set(AUTO_GENERATED_HEADERS_DIR "${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}_AutoGenerated")
    # Allow us to include the auto-generated headers
    target_include_directories(
        ${TARGET_NAME}
        INTERFACE
        "${AUTO_GENERATED_HEADERS_DIR}"
    )

    set_target_properties(
        ${TARGET_NAME}
        PROPERTIES "AUTO_GENERATED_HEADERS_DIR" "${AUTO_GENERATED_HEADERS_DIR}"
    )
endfunction()

# OUTPUT_FILE_NAME is the name that you will include in your code
# e.g. #INCLUDE "test.h" or #include "headertype1/header.h"
# See the self tests CmakeLists.txt to understand how to use
# this function and to learn about its optional arguments
function(cpp11_embed_generate_header
    TARGET_NAME
    INPUT_FILE_PATH
    IDENTIFIER_NAME
    OUTPUT_FILE_NAME
)
    get_property(
        AUTO_GENERATED_HEADERS_DIR_DEFINED TARGET
        ${TARGET_NAME}
        PROPERTY
        "AUTO_GENERATED_HEADERS_DIR"
        SET
    )
    if(NOT ${AUTO_GENERATED_HEADERS_DIR_DEFINED})
        message(FATAL_ERROR "Property AUTO_GENERATED_HEADERS_DIR not found on target ${TARGET_NAME}. Was it created with add_cpp11_embed_target?")
    endif()
    get_target_property(
        AUTO_GENERATED_HEADERS_DIR
        ${TARGET_NAME}
        "AUTO_GENERATED_HEADERS_DIR"
    )
    set(OUTPUT_FILE_PATH "${AUTO_GENERATED_HEADERS_DIR}/${OUTPUT_FILE_NAME}")

    # Get rid of the target name argument
    list(REMOVE_AT ARGV 0)
    # Replace output filename with path that includes the auto-generated
    # headers directory
    list(INSERT ARGV 2 "${OUTPUT_FILE_PATH}")
    list(REMOVE_AT ARGV 3)
    # Forward all arguments
    cpp11_embed_generate_header_no_target(${ARGV})

    # Ensure that the target is aware of all the headers
    # so that they will definitely be generated for us
    target_sources(${TARGET_NAME} PRIVATE "${OUTPUT_FILE_PATH}")
endfunction()