cmake_minimum_required(VERSION 3.0 FATAL_ERROR)

project(microP7)

include(CheckCXXCompilerFlag)
include(CheckCCompilerFlag)

function(enable_cxx_compiler_flag_if_supported flag)
    string(FIND "${CMAKE_CXX_FLAGS}" "${flag}" flag_already_set)
    if(flag_already_set EQUAL -1)
        check_cxx_compiler_flag("${flag}" flag_supported)
        if(flag_supported)
            set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
        endif()
    endif()
    
    string(FIND "${CMAKE_C_FLAGS}" "${flag}" flag_already_set)
    if(flag_already_set EQUAL -1)
        check_c_compiler_flag("${flag}" flag_supported)
        if(flag_supported)
            set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
        endif()
    endif()
endfunction()

set(ROOT_UP7_PATH ${PROJECT_SOURCE_DIR} CACHE INTERNAL "")

if(MSVC)
    add_definitions(-D_UNICODE)
    add_definitions(-DUNICODE)

    if(NOT COMMAND set_ide_folder)
        macro(set_ide_folder _project_name)
            string(LENGTH ${ROOT_UP7_PATH} ROOT_UP7_PATH_LEN)
            string(LENGTH ${CMAKE_CURRENT_SOURCE_DIR} CURRENT_SOURCE_DIR_LEN)
            MATH(EXPR ROOT_UP7_PATH_LEN "${ROOT_UP7_PATH_LEN}+1")
            MATH(EXPR CURRENT_SOURCE_DIR_LEN "${CURRENT_SOURCE_DIR_LEN} - ${ROOT_UP7_PATH_LEN}")

            string(SUBSTRING ${CMAKE_CURRENT_SOURCE_DIR} ${ROOT_UP7_PATH_LEN} ${CURRENT_SOURCE_DIR_LEN} IDE_SUBFOLDER)
            set_property(TARGET ${_project_name} PROPERTY FOLDER ${IDE_SUBFOLDER})

            message(${_project_name})
        endmacro()
    endif()

else()
    enable_cxx_compiler_flag_if_supported("-Wall")
    enable_cxx_compiler_flag_if_supported("-Wextra")
    enable_cxx_compiler_flag_if_supported("-pedantic")
    enable_cxx_compiler_flag_if_supported("-D_FILE_OFFSET_BITS=64")
    enable_cxx_compiler_flag_if_supported("-D_LARGEFILE64_SOURCE")
    enable_cxx_compiler_flag_if_supported("-fvisibility=hidden")
    enable_cxx_compiler_flag_if_supported("-Wno-variadic-macros")
    enable_cxx_compiler_flag_if_supported("-Wno-long-long")
    enable_cxx_compiler_flag_if_supported("-Wno-missing-field-initializers")
    enable_cxx_compiler_flag_if_supported("-Wno-unknown-pragmas")
    
    macro(set_ide_folder _project_name)
    endmacro()
endif()

set_property(GLOBAL PROPERTY USE_FOLDERS ON)

if(uP7_EXTERNAL_INTEGRATION)
else()
    SET(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/_Build_)
endif()

if (TARGET p7)
    #message("P7 target is already existing, scipping local one")
else()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/P7lib")
       add_subdirectory(P7lib)
    else()
        message(FATAL_ERROR "Can't find P7 library!")
    endif()
endif()

add_subdirectory(uP7lib)
add_subdirectory(uP7proxyLib)
add_subdirectory(uP7preProcessor)
add_subdirectory(uP7test)
add_subdirectory(uP7example)
