set (RIZZ_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/rizz/)

function(generate_bundle_file_internal target_name plugins filepath func_name game_name)
    set (code "// This file is auto-generated by bundle.cmake\n")
    set (code "${code}#pragma once\n")
    set (code "${code}#include \"rizz/plugin.h\"\n\n")

    if (game_name)
        set (code "${code}#define GAME_PLUGIN_NAME \"${game_name}\"\n\n")
    endif()

    # fwd declare
    set (code "${code}static void rizz__plugin_register(const rizz_plugin_info*)\;\n")
    foreach (plugin ${plugins})
        set (code "${code}RIZZ_PLUGIN_EXPORT int rizz_plugin_main_${plugin}(rizz_plugin*, rizz_plugin_event)\;\n")
        set (code "${code}RIZZ_PLUGIN_EXPORT void rizz_plugin_event_handler_${plugin}(const rizz_app_event*)\;\n")
        set (code "${code}RIZZ_PLUGIN_EXPORT void rizz_plugin_get_info_${plugin}(rizz_plugin_info*)\;\n")
    endforeach()
    set (code "${code}\n")

    # start 
    set (code "${code}static inline void ${func_name}() {\n")
    set (code "${code}\trizz_plugin_info info\;\n\n")

    foreach (plugin ${plugins})
        set (code "${code}\trizz_plugin_get_info_${plugin}(&info)\;\n")
        set (code "${code}\tinfo.main_cb = rizz_plugin_main_${plugin}\;\n")
        set (code "${code}\tif (info.flags & RIZZ_PLUGIN_INFO_EVENT_HANDLER) info.event_cb = rizz_plugin_event_handler_${plugin}\;\n")
        set (code "${code}\telse                                            info.event_cb = NULL\;\n")
        set (code "${code}\trizz__plugin_register(&info)\;\n")
    endforeach()

    set(code "${code}}\n")
    file (WRITE ${filepath} ${code})
endfunction()

function(bundle_plugins_internal target_name plugins)
    if (BUNDLE AND plugins)
        generate_bundle_file_internal(${target_name} ${plugins} ${RIZZ_SOURCE_DIR}/plugin_bundle_native.h "rizz__plugin_bundle_native" "")
        target_link_libraries(${target_name} PRIVATE ${plugins})
    elseif (plugins)
        add_dependencies(${target_name} ${plugins})
    endif()
endfunction()

function(bundle_plugins target_name plugins)
    if (BUNDLE)
        if (plugins)
            target_link_libraries(${target_name} PRIVATE ${plugins})
            list(APPEND plugins ${target_name})
        else()
            set(plugins ${target_name})
        endif()
        generate_bundle_file_internal(${target_name} ${plugins} ${RIZZ_SOURCE_DIR}/plugin_bundle.h "rizz__plugin_bundle" ${target_name})
        target_link_libraries(${target_name} PRIVATE rizz)   # bundle mode always links with the rizz
        target_compile_definitions(${target_name} PRIVATE -DRIZZ_BUNDLE)
    elseif (plugins)
        add_dependencies(${target_name} ${plugins})
    endif()    
endfunction()