buildscript {
  // Buildscript is evaluated before everything else so we can't use getExtOrDefault
  def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['ComplyCubeSDK_kotlinVersion']
  print "Installing ComplyCube dependency"
  repositories {
      mavenLocal()
      google()
      mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

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


apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'jacoco'

def useNFC = System.getenv("USE_NFC") == "true" ||
        (project.hasProperty("USE_NFC") && project.USE_NFC == "true")

repositories {
  google()
  mavenCentral()
}

task listrepos {
  doLast {
    println "Repositories:"
    project.repositories.each { println "Name: " + it.name + "; url: " + it.url }
  }
}

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

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

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

android {
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault('minSdkVersion')
    targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
  }
  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable 'GradleCompatible'
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  sourceSets {
    main {
      java {
        // Exclude any accidental app-level Application classes shipped in the lib
        exclude '**/MainApplication.*'
      }
    }
  }

}

repositories {
  mavenLocal()
  mavenCentral()
  google()



  def found = false
  def defaultDir = null
  def androidSourcesName = 'React Native sources'

  if (rootProject.ext.has('reactNativeAndroidRoot')) {
    defaultDir = rootProject.ext.get('reactNativeAndroidRoot')
  } else {
    defaultDir = new File(
      projectDir,
      '/../../../node_modules/react-native/android'
    )
  }

  if (defaultDir.exists()) {
    maven {
      url defaultDir.toString()
      name androidSourcesName
    }

    logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}")
    found = true
  } else {
    def parentDir = rootProject.projectDir

    1.upto(5, {
      if (found) return true
      parentDir = parentDir.parentFile

      def androidSourcesDir = new File(
        parentDir,
        'node_modules/react-native'
      )

      def androidPrebuiltBinaryDir = new File(
        parentDir,
        'node_modules/react-native/android'
      )

      if (androidPrebuiltBinaryDir.exists()) {
        maven {
          url androidPrebuiltBinaryDir.toString()
          name androidSourcesName
        }

        logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}")
        found = true
      } else if (androidSourcesDir.exists()) {
        maven {
          url androidSourcesDir.toString()
          name androidSourcesName
        }

        logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}")
        found = true
      }
    })
  }

  if (!found) {
    throw new RuntimeException("${project.name}: unable to locate React Native android sources.")
  }
}

def kotlin_version = getExtOrDefault('kotlinVersion')

dependencies {
    //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-native:+"
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3"
  implementation 'androidx.appcompat:appcompat:1.5.1'
  implementation 'com.google.android.material:material:1.4.0'
  if (useNFC) {
    implementation("com.complycube:complycube-sdk-nfc:+")
    implementation("com.complycube:nfc-plugin:+")
  } else {
    implementation("com.complycube:complycube-sdk:+")
  }
  testImplementation "junit:junit:4.13.2"
  testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  testImplementation "com.google.truth:truth:1.4.0"
  // implementation "com.complycube:complycube-sdk-dev:+"
  // implementation("com.complycube:complycube-sdk-dev:+")

// From node_modules
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "ComplyCubeSDK"
    codegenJavaPackageName = "com.complycubereactnative"
  }
}

jacoco {
  toolVersion = "0.8.11"
}

tasks.register("jacocoTestReport", JacocoReport) {
  dependsOn "testDebugUnitTest"

  reports {
    xml.required = true
    html.required = true
    csv.required = false
  }

  def coverageIncludes = ["com/complycube/reactnative/config/**"]
  def fileFilter = [
    "**/R.class",
    '**/R$*.class',
    "**/BuildConfig.*",
    "**/Manifest*.*",
    "**/*Test*.*",
    "android/**/*.*"
  ]

  def kotlinDebugTree = fileTree(
    dir: "$buildDir/tmp/kotlin-classes/debug",
    includes: coverageIncludes,
    excludes: fileFilter
  )
  def javaDebugTree = fileTree(
    dir: "$buildDir/intermediates/javac/debug/classes",
    includes: coverageIncludes,
    excludes: fileFilter
  )

  classDirectories.setFrom(files([kotlinDebugTree, javaDebugTree]))
  sourceDirectories.setFrom(files(["src/main/java", "src/main/kotlin"]))
  executionData.setFrom(fileTree(dir: buildDir, includes: [
    "jacoco/testDebugUnitTest.exec",
    "outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec"
  ]))
}
