# Copyright (C) 2022 Smirnov Vladimir / mapron1@gmail.com
# SPDX-License-Identifier: MIT
# See LICENSE file for details.

function(GenerateQrcWithTranslations resourceFolder translationsRoot qrcNameOut)
    set(srcDir ${translationsRoot})
    set(destDir ${CMAKE_BINARY_DIR}/assetsCompiled/${resourceFolder})
    set(qrcName ${CMAKE_BINARY_DIR}/assetsCompiled/${resourceFolder}.qrc)
    file(MAKE_DIRECTORY "${destDir}")
    set(masks ${srcDir}/*.ts)
    file(GLOB_RECURSE fileListAbsSrc   ${masks})

    set(QRC_PREFIX ${resourceFolder}) # name is important for .in file
    set(QRC_FILES)                    # name is important for .in file

    set(fileListAbsConfig)
    foreach(tsFileAbs ${fileListAbsSrc})
        string(REPLACE "${srcDir}/" "" relFile "${tsFileAbs}")
        string(REPLACE ".ts" ".qm" relFile "${relFile}")
        set(qmFileAbs "${destDir}/${relFile}")
        list(APPEND fileListAbsConfig ${qmFileAbs})

        add_custom_command(OUTPUT ${qmFileAbs}
                           COMMAND ${Qt5_LRELEASE_EXECUTABLE}
                           ARGS ${tsFileAbs} -qm ${qmFileAbs}
                           MAIN_DEPENDENCY ${tsFileAbs} VERBATIM)

        string(REPLACE "${resourceFolder}/" "" file "${relFile}")
        set(QRC_FILES "${QRC_FILES}<file alias=\"${file}\">${resourceFolder}/${relFile}</file>\n")
	endforeach()

	configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/qrcTemplate.qrc.in ${qrcName} @ONLY )
	source_group("Qt Resource Files" FILES ${qrcName})

	set(${qrcNameOut} ${qrcName} PARENT_SCOPE)
endfunction()

# function for target declaration.
function(AddTarget)
    set(options FH NO_DEFAULT_GLOB QT)
    set(oneValueArgs NAME OUTPUT_NAME ROOT TYPE MAIN_INCLUDE)
    set(multiValueArgs SRC INCLUDES DEPS DEPS_FH OPTIONS DEFINES EXCLUDE_FILES MOC_INCLUDES MOC_DEFINES)
    cmake_parse_arguments(AddTarget "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
    set(sources)
    set(headers)
    set(subdir ${CMAKE_CURRENT_SOURCE_DIR}/)
    if (AddTarget_ROOT)
        set(subdir ${CMAKE_CURRENT_SOURCE_DIR}/${AddTarget_ROOT}/)
    endif()
    set(masksCpp *.cpp *.c ${AddTarget_SRC})
    set(masksHeaders *.hpp *.h)
    if (AddTarget_NO_DEFAULT_GLOB)
        set(masksCpp ${AddTarget_SRC})
        set(masksHeaders)
    endif()
    foreach (maskl ${masksCpp} )
        file(GLOB src ${subdir}${maskl})
        list(APPEND sources ${src})
    endforeach()
    foreach (maskl ${masksHeaders} )
        file(GLOB src ${subdir}${maskl})
        list(APPEND headers ${src})
    endforeach()
    foreach (mask ${AddTarget_EXCLUDE_FILES})
        list(FILTER sources EXCLUDE REGEX ${mask})
    endforeach()
    if (AddTarget_QT)
        file(GLOB uiFiles ${subdir}*.ui)
        source_group("Form Files" FILES ${uiFiles})

        CreateUiRules(generatedUiFiles uiIncludes ${uiFiles})
        list(APPEND AddTarget_INCLUDES ${uiIncludes})

        list(APPEND sources ${uiFiles} )
        set(mocIncludes ${subdir} ${AddTarget_MOC_INCLUDES})
        set(mocDefines ${AddTarget_DEFINES} ${AddTarget_MOC_DEFINES})
        CreateMocRules(sources "mocIncludes" "mocDefines" ${headers} )
    endif()
    set(name ${AddTarget_NAME})
    if (AddTarget_FH)
        set(name ${FH_PREFIX}${name})
    endif()
    if ((AddTarget_TYPE STREQUAL "app") OR (AddTarget_TYPE STREQUAL "console_app"))
        if (WIN32 AND NOT (CMAKE_BUILD_TYPE STREQUAL "Debug") AND NOT (AddTarget_TYPE STREQUAL "console_app"))
            set(w32 "WIN32")
        endif()
        add_executable(${name} ${w32} ${sources} ${headers})
    else()
        if (AddTarget_TYPE STREQUAL "static")
            add_library(${name} STATIC ${sources} ${headers})
        else()
            add_library(${name} SHARED ${sources} ${headers})
            generate_export_header(${name} BASE_NAME ${AddTarget_NAME} EXPORT_FILE_NAME ${AddTarget_NAME}Export.hpp )
        endif()
    endif()
    if (AddTarget_OUTPUT_NAME)
        set_target_properties(${name} PROPERTIES OUTPUT_NAME ${AddTarget_OUTPUT_NAME})
    elseif((AddTarget_TYPE STREQUAL "app"))
        set_target_properties(${name} PROPERTIES OUTPUT_NAME ${AddTarget_NAME})
    endif()
    target_include_directories(${name} PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
    foreach (inc ${AddTarget_INCLUDES})
        target_include_directories(${name} PRIVATE ${inc})
    endforeach()
    if (AddTarget_MAIN_INCLUDE)
        target_include_directories(${name} PUBLIC ${AddTarget_MAIN_INCLUDE})
    else ()
        target_include_directories(${name} PUBLIC ${subdir})
    endif()
    foreach (dep ${AddTarget_DEPS})
        target_link_libraries(${name} PRIVATE ${dep})
    endforeach()
    foreach (dep ${AddTarget_DEPS_FH})
        target_link_libraries(${name} PRIVATE ${FH_PREFIX}${dep})
    endforeach()
    foreach (opt ${AddTarget_OPTIONS})
        target_compile_options(${name} PRIVATE ${opt})
    endforeach()
    foreach (opt ${AddTarget_DEFINES})
        target_compile_definitions(${name} PRIVATE ${opt})
    endforeach()
    if (AddTarget_FH)
        set_property(TARGET ${name} PROPERTY FOLDER ${subdir})
    endif()
    # source_group("SRC" FILES "${sources}")
    if (AddTarget_QT)
        set_target_properties(${name} PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF)
    endif()
    if (AddTarget_TYPE STREQUAL "app")
        install(TARGETS ${name}
                RUNTIME DESTINATION bin
                )
    elseif(AddTarget_TYPE STREQUAL "shared")
        install(TARGETS ${name}
                        RUNTIME DESTINATION bin
                        )
    endif()

    if (AddTarget_FH)
        AddStaticCheckTarget(TARGET_NAME ${name} SOURCE_DIR ${subdir})
    endif()
endfunction()

function(InstallQmlFiles)
	set(modules ${ARGN})
	set(qmlRoot ${_qt5Core_install_prefix})
	foreach(module ${modules})
		set(exc)
		if(CMAKE_BUILD_TYPE STREQUAL "Release")
			set(exc PATTERN *plugind.dll EXCLUDE)
		elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
			set(exc PATTERN  *plugin.dll EXCLUDE)
		endif()
		get_filename_component(subdir ${module} DIRECTORY)
		if (subdir)
			set(subdir /${subdir})
		endif()
		install(DIRECTORY ${qmlRoot}/qml/${module} DESTINATION bin/qml${subdir} PATTERN *.ilk EXCLUDE PATTERN *.pdb EXCLUDE ${exc})
	endforeach()
endfunction()
