cmake_minimum_required(VERSION 3.15)

set(PROJECT_NAME "flutter_webrtc_custom")
project(${PROJECT_NAME} LANGUAGES CXX)

if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.24.0")
  cmake_policy(SET CMP0135 NEW)
endif()

set(PLUGIN_NAME "flutter_webrtc_custom_plugin")

add_definitions(-DLIB_WEBRTC_API_DLL)
add_definitions(-DRTC_DESKTOP_DEVICE)

# ==============================
# 🔥 AUTO DOWNLOAD WEBRTC
# ==============================
set(WEBRTC_URL https://github.com/flutter-webrtc/webrtc-build/releases/download/0.0.1/libwebrtc-windows-x64.zip)
set(WEBRTC_DIR ${CMAKE_BINARY_DIR}/webrtc)

if(NOT EXISTS ${WEBRTC_DIR})
  message(STATUS "Downloading WebRTC...")
  file(DOWNLOAD ${WEBRTC_URL} ${CMAKE_BINARY_DIR}/webrtc.zip SHOW_PROGRESS)

  execute_process(
    COMMAND ${CMAKE_COMMAND} -E tar xzf webrtc.zip
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
  )
endif()

set(WEBRTC_INCLUDE ${WEBRTC_DIR}/include)
set(WEBRTC_LIB ${WEBRTC_DIR}/lib)

# ==============================
# 🔥 PLUGIN SOURCE
# ==============================
add_library(${PLUGIN_NAME} SHARED
  "../common/cpp/src/flutter_common.cc"
  "../common/cpp/src/flutter_data_channel.cc"
  "../common/cpp/src/flutter_data_packet_cryptor.cc"
  "../common/cpp/src/flutter_frame_cryptor.cc"
  "../common/cpp/src/flutter_media_stream.cc"
  "../common/cpp/src/flutter_utf8_sanitize.cc"
  "../common/cpp/src/flutter_peerconnection.cc"
  "../common/cpp/src/flutter_frame_capturer.cc"
  "../common/cpp/src/flutter_video_renderer.cc"
  "../common/cpp/src/flutter_screen_capture.cc"
  "../common/cpp/src/flutter_webrtc.cc"
  "../common/cpp/src/flutter_webrtc_base.cc"

  "flutter_webrtc_custom_plugin.cc"
  "task_runner_windows.cc"
)

# ==============================
# 🔥 INCLUDE
# ==============================
include_directories(
  "${CMAKE_CURRENT_SOURCE_DIR}"
  "${CMAKE_CURRENT_SOURCE_DIR}/../common/cpp/include"
  "${CMAKE_CURRENT_SOURCE_DIR}/../third_party/svpng"
  ${WEBRTC_INCLUDE}
)

apply_standard_settings(${PLUGIN_NAME})

set_target_properties(${PLUGIN_NAME} PROPERTIES
  CXX_VISIBILITY_PRESET hidden
)

target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)

target_include_directories(${PLUGIN_NAME} INTERFACE
  "${CMAKE_CURRENT_SOURCE_DIR}"
  "${CMAKE_CURRENT_SOURCE_DIR}/../common/cpp/include"
  ${WEBRTC_INCLUDE}
)

# ==============================
# 🔥 LINK LIB
# ==============================
target_link_libraries(${PLUGIN_NAME} PRIVATE 
  flutter
  flutter_wrapper_plugin
  ${WEBRTC_LIB}/webrtc.dll.lib
)

# ==============================
# 🔥 COPY DLL
# ==============================
set(flutter_webrtc_custom_bundled_libraries
  "${WEBRTC_LIB}/webrtc.dll"
  PARENT_SCOPE
)