include(CheckCXXCompilerFlag)

# Function to add flag if compiler supports it
function(Check_And_Add_Flag)
	set(TARGET ${ARGV0})

	# Sanitize flag to become cmake variable name
	string (REPLACE "-" "_" NAME ${ARGV1})
	string (SUBSTRING ${NAME} 1 -1 NAME)
	string (FIND ${NAME} "=" EQUALS)
	string (SUBSTRING ${NAME} 0 ${EQUALS} NAME)
	CHECK_CXX_COMPILER_FLAG(${ARGV1} ${NAME})
	if (${NAME}) 
		target_compile_options(${TARGET} PRIVATE ${ARGV1})
	endif()
endfunction()

function(AddCompilerFlags)
	set(TARGET ${ARGV0})

	if (("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang"))
		Check_And_Add_Flag(${TARGET} -fdiagnostics-color=always)
		Check_And_Add_Flag(${TARGET} -Wall)
		Check_And_Add_Flag(${TARGET} -Wextra)
		Check_And_Add_Flag(${TARGET} -Wpedantic)
		Check_And_Add_Flag(${TARGET} -Wconversion)
		Check_And_Add_Flag(${TARGET} -Wsign-conversion)
		Check_And_Add_Flag(${TARGET} -Wcast-align)
		Check_And_Add_Flag(${TARGET} -Wcast-qual)
		Check_And_Add_Flag(${TARGET} -Wctor-dtor-privacy)
		Check_And_Add_Flag(${TARGET} -Wdisabled-optimization)
		Check_And_Add_Flag(${TARGET} -Wdouble-promotion)
		Check_And_Add_Flag(${TARGET} -Wduplicated-branches)
		Check_And_Add_Flag(${TARGET} -Wduplicated-cond)
		Check_And_Add_Flag(${TARGET} -Wformat=2)
		Check_And_Add_Flag(${TARGET} -Wlogical-op)
		Check_And_Add_Flag(${TARGET} -Wmissing-include-dirs)
		Check_And_Add_Flag(${TARGET} -Wnoexcept)
		Check_And_Add_Flag(${TARGET} -Wnull-dereference)
		Check_And_Add_Flag(${TARGET} -Wold-style-cast)
		Check_And_Add_Flag(${TARGET} -Woverloaded-virtual)
		Check_And_Add_Flag(${TARGET} -Wshadow)
		Check_And_Add_Flag(${TARGET} -Wstrict-aliasing=1)
		Check_And_Add_Flag(${TARGET} -Wstrict-null-sentinel)
		Check_And_Add_Flag(${TARGET} -Wstrict-overflow=2)
		Check_And_Add_Flag(${TARGET} -Wswitch-default)
		Check_And_Add_Flag(${TARGET} -Wundef)
		Check_And_Add_Flag(${TARGET} -Wuseless-cast)
		Check_And_Add_Flag(${TARGET} -Wno-unknown-pragmas)
		Check_And_Add_Flag(${TARGET} -Wno-aligned-new)
		if(("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") AND (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0))
			# Useless flag that hits a bunch of valid code
			Check_And_Add_Flag(${TARGET} -Wno-missing-field-initializers)
		endif()
		if(FTL_WERROR)
			Check_And_Add_Flag(${TARGET} -Werror)
		endif()
	else()
		Check_And_Add_Flag(${TARGET} /W4)
		Check_And_Add_Flag(${TARGET} /wd4324)
		if(FTL_WERROR)
			Check_And_Add_Flag(${TARGET} /WX)
		endif()
	endif()
endfunction()
