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

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

def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
if (expoModulesCorePlugin.exists()) {
  apply from: expoModulesCorePlugin
  applyKotlinExpoModulesCorePlugin()
  // Remove this check, but keep the contents after SDK49 support is dropped
  if (safeExtGet("expoProvidesDefaultConfig", false)) {
    useExpoPublishing()
    useCoreDependencies()
  }
}

def SQLITE_VERSION = '3420000'
def customDownloadsDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR")
def downloadsDir = customDownloadsDir ? new File(customDownloadsDir) : new File("$buildDir/downloads")
def SQLITE3_SRC_DIR = new File("$buildDir/sqlite3_src")

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

buildscript {
  // 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.5.0")
  }
}

// Remove this if and it's contents, when support for SDK49 is dropped
if (!safeExtGet("expoProvidesDefaultConfig", false)) {
  afterEvaluate {
    publishing {
      publications {
        release(MavenPublication) {
          from components.release
        }
      }
      repositories {
        maven {
          url = mavenLocal().url
        }
      }
    }
  }
}

android {
  // Remove this if and it's contents, when support for SDK49 is dropped
  if (!safeExtGet("expoProvidesDefaultConfig", false)) {
    compileSdkVersion safeExtGet("compileSdkVersion", 34)

    defaultConfig {
      minSdkVersion safeExtGet("minSdkVersion", 23)
      targetSdkVersion safeExtGet("targetSdkVersion", 34)
    }

    publishing {
      singleVariant("release") {
        withSourcesJar()
      }
    }

    lintOptions {
      abortOnError false
    }
  }

  def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION
  if (agpVersion.tokenize('.')[0].toInteger() < 8) {
    compileOptions {
      sourceCompatibility JavaVersion.VERSION_11
      targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
      jvmTarget = JavaVersion.VERSION_11.majorVersion
    }
  }

  namespace "expo.modules.sqlite"
  defaultConfig {
    versionCode 18
    versionName "13.1.1"

    externalNativeBuild {
      cmake {
        abiFilters (*reactNativeArchitectures())
        arguments "-DANDROID_STL=c++_shared",
          "-DSQLITE3_SRC_DIR=${SQLITE3_SRC_DIR}"
      }
    }
  }
  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }
  buildFeatures {
    prefab true
  }
}

dependencies {
  // Remove this if and it's contents, when support for SDK49 is dropped
  if (!safeExtGet("expoProvidesDefaultConfig", false)) {
    implementation project(':expo-modules-core')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${getKotlinVersion()}"
  }

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

def createNativeDepsDirectories = tasks.register('createNativeDepsDirectories') {
  downloadsDir.mkdirs()
  SQLITE3_SRC_DIR.mkdirs()
}

def downloadSQLite = tasks.create('downloadSQLite', Download) {
  dependsOn(createNativeDepsDirectories)
  src("https://www.sqlite.org/2023/sqlite-amalgamation-${SQLITE_VERSION}.zip")
  onlyIfNewer(true)
  overwrite(false)
  dest(new File(downloadsDir, "sqlite-amalgamation-${SQLITE_VERSION}.zip"))
}

def prepareSQLite = tasks.register('prepareSQLite', Copy) {
  dependsOn(downloadSQLite)
  from(zipTree(downloadSQLite.dest))
  into(SQLITE3_SRC_DIR)
  eachFile {
    // flatten files
    path = name
  }
}

void nativeBuildDependsOn(project, dependsOnTask) {
  def buildTasks = project.tasks.findAll { task ->
    def taskName = task.name
    if (taskName.contains("Clean")) { return false }
    if (taskName.contains("externalNative") || taskName.contains("CMake") || taskName.contains("generateJsonModel")) {
      return true
    }
    return false
  }
  buildTasks.forEach { task -> task.dependsOn(dependsOnTask) }
}

afterEvaluate {
  nativeBuildDependsOn(project, prepareSQLite)
}
