import java.nio.file.Paths

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'maven-publish'
apply plugin: "de.undercouch.download"

group = 'host.exp.exponent'
version = '13.2.1'

def REACT_NATIVE_BUILD_FROM_SOURCE = findProject(":ReactAndroid") != null
def REACT_NATIVE_DIR = REACT_NATIVE_BUILD_FROM_SOURCE
  ? findProject(":ReactAndroid").getProjectDir().parent
  : new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).parent
def RN_SO_DIR = REACT_NATIVE_BUILD_FROM_SOURCE
  ? Paths.get(findProject(":ReactAndroid").getProjectDir().toString(), "build", "intermediates", "library_*", "*", "jni")
  : "${buildDir}/react/jni"

def reactProperties = new Properties()
file("$REACT_NATIVE_DIR/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
def REACT_NATIVE_VERSION = System.getenv("REACT_NATIVE_OVERRIDE_VERSION") ?: reactProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_TARGET_VERSION = REACT_NATIVE_VERSION.split("\\.")[1].toInteger()

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

buildscript {
  def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
  if (expoModulesCorePlugin.exists()) {
    apply from: expoModulesCorePlugin
    applyKotlinExpoModulesCorePlugin()
  }

  // Simple helper that allows the root project to override versions declared by this library.
  ext.safeExtGet = { prop, fallback ->
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
  }

  // Ensures backward compatibility
  ext.getKotlinVersion = {
    if (ext.has("kotlinVersion")) {
      ext.kotlinVersion()
    } else {
      ext.safeExtGet("kotlinVersion", "1.8.10")
    }
  }

  repositories {
    mavenCentral()
  }

  dependencies {
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${getKotlinVersion()}")
    classpath("de.undercouch:gradle-download-task:5.3.0")
  }
}

// Creating sources with comments
task androidSourcesJar(type: Jar) {
  classifier = 'sources'
  from android.sourceSets.main.java.srcDirs
}

afterEvaluate {
  publishing {
    publications {
      release(MavenPublication) {
        from components.release
        // Add additional sourcesJar to artifacts
        artifact(androidSourcesJar)
      }
    }
    repositories {
      maven {
        url = mavenLocal().url
      }
    }
  }
}

android {
  compileSdkVersion safeExtGet("compileSdkVersion", 33)

  if (rootProject.hasProperty("ndkPath")) {
    ndkPath rootProject.ext.ndkPath
  }
  if (rootProject.hasProperty("ndkVersion")) {
    ndkVersion rootProject.ext.ndkVersion
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
  }

  kotlinOptions {
    jvmTarget = JavaVersion.VERSION_11.majorVersion
  }

  defaultConfig {
    minSdkVersion safeExtGet("minSdkVersion", 21)
    targetSdkVersion safeExtGet("targetSdkVersion", 33)
    versionCode 24
    versionName "13.2.1"

    externalNativeBuild {
      cmake {
        cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
        abiFilters (*reactNativeArchitectures())
        arguments "-DANDROID_STL=c++_shared",
            "-DREACT_NATIVE_DIR=${REACT_NATIVE_DIR}",
            "-DRN_SO_DIR=${RN_SO_DIR}"
      }
    }
  }

  externalNativeBuild {
    cmake {
      if (REACT_NATIVE_TARGET_VERSION >= 71) {
        path "CMakeLists.txt"
      } else {
        path "legacy/CMakeLists.txt"
      }
    }
  }

  buildFeatures {
    prefab true
  }

  packagingOptions {
    // Gradle will add cmake target dependencies into packaging.
    // Theses files are intermediated linking files to build reanimated and should not be in final package.
    excludes += [
        "**/libc++_shared.so",
        "**/libreactnativejni.so",
        "**/libglog.so",
        "**/libjscexecutor.so",
        "**/libfbjni.so",
        "**/libfolly_json.so",
        "**/libhermes.so",
        "**/libjsi.so",
    ]
  }

  lintOptions {
    abortOnError false
  }
  testOptions {
    unitTests.all {
      useJUnitPlatform()
    }
  }
}

dependencies {
  implementation project(':expo-modules-core')

  implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${getKotlinVersion()}"

  //noinspection GradleDynamicVersion
  implementation 'com.facebook.react:react-native:+'

  compileOnly 'com.facebook.fbjni:fbjni:0.3.0'

  api 'com.google.android.exoplayer:exoplayer:2.18.1'
  api 'com.google.android.exoplayer:extension-okhttp:2.18.1'

  api "com.squareup.okhttp3:okhttp:3.14.9"
  api "com.squareup.okhttp3:okhttp-urlconnection:3.14.9"

  testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.1'
  testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.5.1"

  testImplementation 'io.mockk:mockk:1.12.3'
}

if (REACT_NATIVE_TARGET_VERSION < 71) {
  applyLegacyReactNativeLibsExtractionPlugin()
}
