include(Logging)

function(add_shared_cxx_flags)
    foreach(flag ${ARGN})
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
        set(CM_SHARED_CXX_FLAGS "${CM_SHARED_CXX_FLAGS} ${flag}" PARENT_SCOPE)
    endforeach()
endfunction()

function(add_cxx_flags)
    foreach(flag ${ARGN})
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
    endforeach()
endfunction()

function(add_c_flags)
    foreach(flag ${ARGN})
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
    endforeach()
endfunction()

function(add_shared_c_flags)
    foreach(flag ${ARGN})
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
        set(CM_SHARED_C_FLAGS "${CM_SHARED_C_FLAGS} ${flag}" PARENT_SCOPE)
    endforeach()
endfunction()

function(set_default_compiler_flags)
    if(NOT DEFINED CM_SHARED_C_FLAGS)
        set(CM_SHARED_C_FLAGS "")
    endif()
    if(NOT DEFINED CM_SHARED_CXX_FLAGS)
        set(CM_SHARED_CXX_FLAGS "")
    endif()
    add_cxx_flags(--std=c++11)
    add_c_flags(--std=c11)
    if("${CMAKE_BUILD_TYPE}" STREQUAL "RELEASE")
        add_shared_cxx_flags(-O2)
        add_shared_c_flags(-O2)
    elseif("${CMAKE_BUILD_TYPE}" STREQUAL "DEBUG")
        add_shared_cxx_flags(-O0 -g)
        add_shared_c_flags(-O0 -g)
    else()
        message(FATAL_ERROR "Unknown build type: '${CMAKE_BUILD_TYPE}'")
    endif()

    if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
        # only specify -stdlib if not already defined
        if(NOT "${CMAKE_CXX_FLAGS}" MATCHES ".*-stdlib.*")
            add_cxx_flags(-stdlib=libstdc++)
        endif()
    endif()

    log_info("flags: ${CMAKE_CXX_FLAGS_DEBUG} || ${CMAKE_CXX_FLAGS_RELEASE}")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE)
    set(CM_SHARED_CXX_FLAGS "${CM_SHARED_CXX_FLAGS}" PARENT_SCOPE)
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}" PARENT_SCOPE)
    set(CM_SHARED_C_FLAGS "${CM_SHARED_C_FLAGS}" PARENT_SCOPE)
endfunction()
