import groovy.json.JsonSlurper
import org.apache.tools.ant.filters.ReplaceTokens

buildscript {

  repositories {
    google()
    mavenCentral()

    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:4.2.1'
  }
}

apply plugin: 'com.android.library'

def getExtOrDefault(name, defaultValue) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : defaultValue
}

android {
  compileSdkVersion getExtOrDefault('compileSdkVersion', 28)

  defaultConfig {
    minSdkVersion getExtOrDefault('minSdkVersion', 16)
    targetSdkVersion getExtOrDefault('targetSdkVersion', 28)

    externalNativeBuild {
      cmake {
        cppFlags "-fexceptions", "-frtti", "-std=c++1y", "-DONANDROID"
        abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
        arguments '-DANDROID_STL=c++_shared', "-DNODE_MODULES_DIR=${rootDir}/../node_modules"
      }
    }
  }

  lintOptions{
    abortOnError false
  }

  externalNativeBuild {
     cmake {
          path "./src/main/rnmmkv/CMakeLists.txt"
      }
  }

  packagingOptions {
    excludes = ["**/libc++_shared.so","**/libreactnativeutilsjni.so"]
  }
  
  configurations {
    extractHeaders
    extractJNI
  }
}

repositories {
  mavenCentral()
  mavenLocal()
  
  maven {
    // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
    url "$rootDir/../node_modules/react-native/android"
  }
  google()  
}

dependencies {
  //noinspection GradleDynamicVersion
  implementation 'com.facebook.react:react-native:+'
  implementation "com.scottyab:secure-preferences-lib:0.1.4"
  implementation 'com.google.code.gson:gson:2.8.6'

  def rnAAR = fileTree("${rootDir}/../node_modules/react-native/android").matching({ it.include "**/**/*.aar" }).singleFile
  
  def inputFile = new File(rootDir, '../node_modules/react-native/package.json')
  def json = new JsonSlurper().parseText(inputFile.text)
  def reactNativeVersion = json.version as String
  def (major, minor, patch) = reactNativeVersion.tokenize('.')
  extractJNI(files(rnAAR))
}

task extractAARHeaders {
  doLast {
    configurations.extractHeaders.files.each {
      def file = it.absoluteFile
      copy {
        from zipTree(file)
        into "$buildDir/$file.name"
        include "**/*.h"
      }
    }
  }
}

task extractJNIFiles {
  doLast {
    configurations.extractJNI.files.each {
      def file = it.absoluteFile

      copy {
        from zipTree(file)
        into "$buildDir/$file.name"
        include "jni/**/*"
      }
    }
  }
}

tasks.whenTaskAdded { task ->
  if (task.name.contains('externalNativeBuild')) {
    task.dependsOn(extractAARHeaders)
    task.dependsOn(extractJNIFiles)
  }
}

