# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
if(FLAC_INCLUDE_DIR)
  set(FLAC_FIND_QUIETLY TRUE)
endif()

find_package(Ogg QUIET)

find_path(FLAC_INCLUDE_DIR FLAC/stream_decoder.h)
find_path(FLACPP_INCLUDE_DIR FLAC++/metadata.h)
find_library(FLAC_LIBRARY NAMES FLAC)
find_library(FLACPP_LIBRARY NAMES FLAC++)

include (FindPackageHandleStandardArgs)
find_package_handle_standard_args(FLAC REQUIRED_VARS FLAC_LIBRARY FLACPP_LIBRARY FLAC_INCLUDE_DIR FLACPP_INCLUDE_DIR OGG_FOUND)

if(FLAC_FOUND)
  set(HAVE_FLAC 1)
  if(WIN32)
    set(FLAC_DEFINITIONS -DFLAC__NO_DLL)
    set(FLAC_INTERFACE_LIBRARIES Ogg::Ogg ws2_32)
  else()
    set(FLAC_DEFINITIONS)
    set(FLAC_INTERFACE_LIBRARIES Ogg::Ogg)
  endif()
  set(FLAC_LIBRARIES ${FLACPP_LIBRARY} ${FLAC_LIBRARY} ${FLAC_INTERFACE_LIBRARIES})

  set(_CMAKE_REQUIRED_LIBRARIES_TMP ${CMAKE_REQUIRED_LIBRARIES})
  set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${FLAC_LIBRARIES} ${OGG_LIBRARY})
  set(_CMAKE_REQUIRED_INCLUDES_TMP ${CMAKE_REQUIRED_INCLUDES})
  set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES} ${FLACPP_INCLUDE_DIR})
  set(_CMAKE_REQUIRED_DEFINITIONS_TMP ${CMAKE_REQUIRED_DEFINITIONS})
  set(CMAKE_REQUIRED_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} ${FLAC_DEFINITIONS})
  CHECK_CXX_SOURCE_COMPILES("#include <FLAC++/metadata.h>\nint main() {\n  FLAC::Metadata::VorbisComment vc;\n  const ::FLAC__StreamMetadata* fsmd = vc;\n  return 0;\n}\n" FLAC_STREAMMETADATA_OPERATOR_FOUND)
  CHECK_CXX_SOURCE_COMPILES("#include <FLAC++/metadata.h>\nint main() {\n  FLAC::Metadata::Picture pic;\n  return 0;\n}\n" FLAC_METADATA_PICTURE_FOUND)
  set(CMAKE_REQUIRED_LIBRARIES ${_CMAKE_REQUIRED_LIBRARIES_TMP})
  set(CMAKE_REQUIRED_INCLUDES ${_CMAKE_REQUIRED_INCLUDES_TMP})
  set(CMAKE_REQUIRED_DEFINITIONS ${_CMAKE_REQUIRED_DEFINITIONS_TMP})

  if(NOT FLAC_STREAMMETADATA_OPERATOR_FOUND)
    set(HAVE_NO_FLAC_STREAMMETADATA_OPERATOR 1)
  endif()
  if(FLAC_METADATA_PICTURE_FOUND)
    set(HAVE_FLAC_PICTURE 1)
  endif()

  if(NOT TARGET FLAC::FLAC)
    add_library(FLAC::FLAC UNKNOWN IMPORTED)
    string(REPLACE "-D" "" FLAC_COMPILE_DEFINITIONS "${FLAC_DEFINITIONS}")
    set_target_properties(FLAC::FLAC PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${FLAC_INCLUDE_DIR}"
      IMPORTED_LOCATION "${FLAC_LIBRARY}"
      INTERFACE_LINK_LIBRARIES "${FLAC_INTERFACE_LIBRARIES}"
      INTERFACE_COMPILE_DEFINITIONS "${FLAC_COMPILE_DEFINITIONS}"
    )
  endif()
  if(NOT TARGET FLACPP::FLACPP)
    add_library(FLACPP::FLACPP UNKNOWN IMPORTED)
    set_target_properties(FLACPP::FLACPP PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${FLACPP_INCLUDE_DIR}"
      IMPORTED_LOCATION "${FLACPP_LIBRARY}"
      INTERFACE_LINK_LIBRARIES FLAC::FLAC
    )
  endif()
endif()

mark_as_advanced(FLAC_INCLUDE_DIR FLACPP_INCLUDE_DIR FLAC_LIBRARY FLACPP_LIBRARY)
