cmake_minimum_required(VERSION 3.20)
project(ISXMr VERSION 1.0.0 LANGUAGES CXX)

# Include the FetchContent module
include(FetchContent)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Set the project source directory
set(SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)

# Set the project include directory
include_directories(${SOURCE_DIR})

file(GLOB_RECURSE SCRIPT_FILES "scripts/*.iss")
file(GLOB_RECURSE LGUI2_FILES "lgui2/*.json")

function(create_resources dir output)
    # Create empty output file
    file(WRITE ${output} "")
    # Collect input files
    file(GLOB bins ${dir}/*)
    # Iterate through input files
    foreach(bin ${bins})
        # Get short filename
        string(REGEX MATCH "([^/]+)$" filename ${bin})
        # Replace filename spaces & extension separator for C compatibility
        string(REGEX REPLACE "\\.| |-" "_" filename ${filename})
        # Read hex data from file
        file(READ ${bin} filedata HEX)
        # Convert hex data for C compatibility
        string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," filedata ${filedata})
        # Append data to output file
        file(APPEND ${output} "const unsigned char ${filename}[] = {${filedata}};\nconst unsigned ${filename}_size = sizeof(${filename});\n")
    endforeach()
endfunction()

create_resources(scripts/ ${SOURCE_DIR}/scripts.h)
create_resources(lgui2/ ${SOURCE_DIR}/lgui2.h)

# foreach(FILE ${SCRIPT_FILES})
#     get_filename_component(FILE_NAME ${FILE} NAME)
#     string(REGEX REPLACE "[^a-zA-Z0-9]" "_" FILE_IDENTIFIER ${FILE_NAME})
#     set(HEADER_FILE "${CMAKE_CURRENT_SOURCE_DIR}/scripts/${FILE_NAME}.h")

#     add_custom_command(
#         OUTPUT ${HEADER_FILE}
#         COMMENT "Generating ${HEADER_FILE} from ${FILE}"
#         COMMAND PowerShell -Command "$bytes = [System.IO.File]::ReadAllBytes('${FILE}'); $header = 'unsigned char ${FILE_IDENTIFIER}[] = {' + ($bytes -join ', ') + '}; unsigned int ${FILE_IDENTIFIER}_len = ' + $bytes.Length + ';' > ${HEADER_FILE}"
#         WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
#         DEPENDS ${FILE}
#     )

#     list(APPEND GENERATED_HEADERS ${HEADER_FILE})
# endforeach()

# foreach(FILE ${LGUI2_FILES})
#     get_filename_component(FILE_NAME ${FILE} NAME)
#     string(REGEX REPLACE "[^a-zA-Z0-9]" "_" FILE_IDENTIFIER ${FILE_NAME})
#     set(HEADER_FILE "${CMAKE_CURRENT_SOURCE_DIR}/lgui2/${FILE_NAME}.h")
#     file(TIMESTAMP "${FILE}" MODIFICATION_TIME "%Y-%m-%d %H:%M:%S")

#     add_custom_command(
#         OUTPUT ${HEADER_FILE}
#         COMMENT "Generating ${HEADER_FILE} from ${FILE}"
#         COMMAND ${CMAKE_COMMAND} -E remove ${HEADER_FILE}
#         COMMAND PowerShell -Command "$bytes = [System.IO.File]::ReadAllBytes('${FILE}'); $header = 'unsigned char ${FILE_IDENTIFIER}[] = {' + ($bytes -join ', ') + '}; unsigned int ${FILE_IDENTIFIER}_len = ' + $bytes.Length + ';' > ${HEADER_FILE}"
#         COMMAND ${CMAKE_COMMAND} -D IDENTIFIER:string="${FILE_IDENTIFIER}" -D HEADER_FILE:string="${HEADER_FILE}" -D MODIFICATION_TIME:string="${MODIFICATION_TIME}" -P ${CMAKE_CURRENT_SOURCE_DIR}/append_timestamp.cmake
#         WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
#         DEPENDS ${FILE}
#     )

#     list(APPEND GENERATED_HEADERS ${HEADER_FILE})
# endforeach()
add_custom_target(GenerateHeaders ALL DEPENDS ${GENERATED_HEADERS})

file(GLOB_RECURSE ISXMr_SOURCES ${SOURCE_DIR}/*.cpp ${SOURCE_DIR}/*.h)
add_library(ISXMr SHARED ${ISXMr_SOURCES})

IF (WIN32)
    cmake_host_system_information(
            RESULT InnerspacePath
            QUERY WINDOWS_REGISTRY
            "HKLM/SOFTWARE/WOW6432Node/Microsoft/Windows/CurrentVersion/App Paths/InnerSpace.exe"
            VALUE
            "PATH"
    )
    if (InnerspacePath)
        # Normalize the path (optional, but recommended)
        file(TO_CMAKE_PATH "${InnerspacePath}" NormalizedInnerspacePath)

        add_custom_command(TARGET ISXMr POST_BUILD
                COMMENT "Copying isxmr.dll to ${NormalizedInnerspacePath}"
                COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:ISXMr> "${NormalizedInnerspacePath}/x64/Extensions/ISXDK35/ISXMr.dll"
        )
    endif ()
endif ()

# Set the path to additional libraries
set(LIBS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs)
set(INCLUDES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/includes)
set(ISXDK_LIBRARY ${LIBS_DIR}/isxdk/lib64/vs16/ISXDK.lib)

set(ISUI_LIBRARY ${LIBS_DIR}/isxdk/lib64/vs16/ISUI.lib)


# Set include directories for isxdk
include_directories(${LIBS_DIR}/isxdk/include)
include_directories(${LIBS_DIR}/argh)
include_directories(${INCLUDES_DIR})


# Link ISXMr with isxdk library
target_link_libraries(ISXMr PRIVATE ${ISUI_LIBRARY} ${ISXDK_LIBRARY})
target_compile_definitions(ISXMr PRIVATE NOMINMAX JS_STL_MAP)
# Set the output directory for the shared library
set_target_properties(ISXMr PROPERTIES
        LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin
)

set_property(TARGET ISXMr PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")