add_library(libSceConvertKeycode SHARED EXCLUDE_FROM_ALL Export.cpp)
target_include_directories(libSceConvertKeycode PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(libSceConvertKeycode PRIVATE libSceUserService)
configure_windows_unwind(libSceConvertKeycode)

if(BUILD_TESTING)
    add_test_executable(guest_convert_keycode_tests ${LIBS_INCLUDE_DIR}/tests/GuestConvertKeycode.cpp)
    target_include_directories(guest_convert_keycode_tests PRIVATE ${LIBS_INCLUDE_DIR})
    target_link_libraries(guest_convert_keycode_tests PRIVATE libSceConvertKeycode libSceUserService libSceSystemService libc)
    configure_windows_unwind(guest_convert_keycode_tests)
    add_test(NAME guest_convert_keycode COMMAND guest_convert_keycode_tests)
    if(WIN32)
        set_tests_properties(guest_convert_keycode PROPERTIES ENVIRONMENT_MODIFICATION
            "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceConvertKeycode>")
    endif()
    add_test_executable(guest_convert_keycode_title_tests ${LIBS_INCLUDE_DIR}/tests/GuestConvertKeycodeTitle.cpp)
    target_include_directories(guest_convert_keycode_title_tests PRIVATE ${LIBS_INCLUDE_DIR})
    target_link_libraries(guest_convert_keycode_title_tests PRIVATE libSceConvertKeycode libSceUserService libSceSystemService libc)
    configure_windows_unwind(guest_convert_keycode_title_tests)
    string(REPEAT "T" 130 convertKeycodeLongTitle)
    foreach(titleCase IN ITEMS oversized-id oversized-title cusa ppsa malformed-json missing)
        set(titleRun ${CMAKE_CURRENT_BINARY_DIR}/convert_keycode_title_${titleCase})
        file(REMOVE_RECURSE ${titleRun})
        file(MAKE_DIRECTORY ${titleRun})
        if(titleCase STREQUAL "oversized-id")
            file(WRITE ${titleRun}/app0/sce_sys/param.json "{\"titleId\": \"CUSA0123456789012345\", \"localizedParameters\": {\"en-US\": {\"titleName\": \"Fixture\"}}}")
        elseif(titleCase STREQUAL "oversized-title")
            file(WRITE ${titleRun}/app0/sce_sys/param.json "{\"titleId\": \"PPSA00000\", \"localizedParameters\": {\"en-US\": {\"titleName\": \"${convertKeycodeLongTitle}\"}}}")
        elseif(titleCase STREQUAL "cusa" OR titleCase STREQUAL "ppsa")
            string(TOUPPER ${titleCase} titlePrefix)
            file(WRITE ${titleRun}/app0/sce_sys/param.json "{\"titleId\": \"${titlePrefix}00000\", \"localizedParameters\": {\"en-US\": {\"titleName\": \"Fixture\"}}}")
        elseif(titleCase STREQUAL "malformed-json")
            file(WRITE ${titleRun}/app0/sce_sys/param.json "{")
        endif()
        add_test(NAME guest_convert_keycode_title_${titleCase} COMMAND guest_convert_keycode_title_tests WORKING_DIRECTORY ${titleRun})
        if(WIN32)
            set_tests_properties(guest_convert_keycode_title_${titleCase} PROPERTIES ENVIRONMENT_MODIFICATION
                "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceConvertKeycode>")
        endif()
    endforeach()
endif()
