buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
    google()
    mavenCentral()
  }

  dependencies {
    classpath("com.android.tools.build:gradle")
    classpath("com.facebook.react:react-native-gradle-plugin")
  }
}

def isNewArchitectureEnabled() {
  return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
}

apply plugin: "com.android.library"

if (isNewArchitectureEnabled()) {
  apply plugin: "com.facebook.react"
}


import java.nio.file.Paths

static def findNodeModules(baseDir) {
  def basePath = baseDir.toPath().normalize()
  // Node's module resolution algorithm searches up to the root directory,
  // after which the base path will be null
  while (basePath) {
    def nodeModulesPath = Paths.get(basePath.toString(), "node_modules")
    def reactNativePath = Paths.get(nodeModulesPath.toString(), "react-native")
    if (nodeModulesPath.toFile().exists() && reactNativePath.toFile().exists()) {
      return nodeModulesPath.toString()
    }
    basePath = basePath.getParent()
  }
  throw new GradleException("React-Native-Skia-Video: Failed to find node_modules/ path!")
}

def nodeModules = findNodeModules(projectDir)
logger.warn("react-native-skia-video: node_modules/ found at: ${nodeModules}")

def reactProperties = new Properties()
file("$nodeModules/react-native/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
def FULL_RN_VERSION =  (System.getenv("REACT_NATIVE_OVERRIDE_VERSION") ?: reactProperties.getProperty("VERSION_NAME"))
def REACT_NATIVE_VERSION = FULL_RN_VERSION.split("\\.")[1].toInteger()
logger.warn("react-native-skia-video: React Native version: ${REACT_NATIVE_VERSION}")


def buildType = "debug"
tasks.all({ task ->
  if (task.name == "buildCMakeRelease") {
    buildType = "release"
  }
})

def getExtOrDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["ReactNativeSkiaVideo_" + name]
}

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["ReactNativeSkiaVideo_" + name]).toInteger()
}

def supportsNamespace() {
  def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
  def major = parsed[0].toInteger()
  def minor = parsed[1].toInteger()

  // Namespace support was added in 7.3.0
  return (major == 7 && minor >= 3) || major >= 8
}

def reactNativeArchitectures() {
  def value = project.getProperties().get("reactNativeArchitectures")
  return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
  if (supportsNamespace()) {
    namespace "com.azzapp.rnskv"

    sourceSets {
      main {
        manifest.srcFile "src/main/AndroidManifestNew.xml"
      }
    }
  }

  ndkVersion getExtOrDefault("ndkVersion")
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

    externalNativeBuild {
      cmake {
        cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
        arguments "-DANDROID_STL=c++_shared",
          "-DNODE_MODULES_DIR=${nodeModules}",
          "-DREACT_NATIVE_VERSION=${REACT_NATIVE_VERSION}",
          "-DBUILD_TYPE=${buildType}"
        abiFilters (*reactNativeArchitectures())
      }
    }
  }

  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }

  packagingOptions {
    doNotStrip buildType == 'debug' ? "**/**/*.so" : ''
    excludes = [
      "META-INF",
      "META-INF/**",
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libjsi.so",
      "**/libfolly_json.so",
      "**/libfolly_runtime.so",
      "**/libglog.so",
      "**/libhermes.so",
      "**/libhermes-executor-debug.so",
      "**/libhermes_executor.so",
      "**/libreactnativejni.so",
      "**/libturbomodulejsijni.so",
      "**/libreact_nativemodule_core.so",
      "**/libjscexecutor.so",
      "**/libruntimeexecutor.so"
    ]
  }

  buildFeatures {
    prefab true
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  sourceSets {
    main {
      if (isNewArchitectureEnabled()) {
        java.srcDirs += [
          "src/newarch",
          // This is needed to build Kotlin project with NewArch enabled
          "${project.buildDir}/generated/source/codegen/java"
        ]
      } else {
        java.srcDirs += ["src/oldarch"]
      }
    }
  }
}

repositories {
  mavenCentral()
  google()
}

def MEDIA3_VERSION = "1.2.1"
dependencies {
  implementation 'com.facebook.react:react-android:+'
  implementation "androidx.media3:media3-exoplayer:${MEDIA3_VERSION}"
  implementation "androidx.media3:media3-datasource:${MEDIA3_VERSION}"
  implementation "androidx.media3:media3-exoplayer-hls:${MEDIA3_VERSION}"
}

tasks.whenTaskAdded { task ->
  if (task.name.contains("configureCMakeDebug")) {
    rootProject.getTasksByName("packageReactNdkDebugLibs", true).forEach {
      task.dependsOn(it)
    }
  }

  if (task.name.contains("configureCMakeRel")) {
    rootProject.getTasksByName("packageReactNdkReleaseLibs", true).forEach {
      task.dependsOn(it)
    }
  }
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "ReactNativeSkiaVideo"
    codegenJavaPackageName = "com.azzapp.rnskv"
  }
}