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["WalkthroughSwiper_kotlinVersion"]

  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.1"
    // noinspection DifferentKotlinGradleVersion
    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"

import groovy.json.JsonSlurper

// https://github.com/callstack/react-native-builder-bob/discussions/359
def registrationCompat = {
  def reactNativeManifest = file("$projectDir/../node_modules/react-native/package.json").exists()
    ? file("$projectDir/../node_modules/react-native/package.json") // developer mode, to run example app
    : file("$projectDir/../../react-native/package.json")
  def reactNativeVersion = new JsonSlurper().parseText(reactNativeManifest.text).version as String
  // Fabric was introduced at react-native@0.68, full CMake support were introduced at react-native@0.70
  // Use Android.mk for compatibility with react-native@0.68/0.69
  reactNativeVersion.matches('(0.68.*|0.69.*)')
}()

def codegenViewLibraryName = "WalkthroughSwiperView"
def codegenViewModuleName = {
  // Autolink for Fabric uses codegenConfig.name in package.json since react-native@0.70
  // Use codegenViewLibraryName for compatibility with react-native@0.68/0.69
  def libraryManifestJson = new JsonSlurper().parseText(file("$projectDir/../package.json").text)
  registrationCompat ? codegenViewLibraryName : libraryManifestJson.codegenConfig.name
}()

def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }

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

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

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["WalkthroughSwiper_" + 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
  if (major == 7 && minor >= 3) {
    return true
  }

  return major >= 8
}

android {
  if (supportsNamespace()) {
    namespace "com.walkthroughswiper"

    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()
    buildConfigField "String", "CODEGEN_MODULE_REGISTRATION", (isNewArchitectureEnabled() && registrationCompat ? "\"${codegenViewModuleName}_registration\"" : "null")
    if (isNewArchitectureEnabled() && registrationCompat) {
      def reactAndroidProject = project(':ReactAndroid')
      externalNativeBuild {
        ndkBuild {
          arguments "APP_PLATFORM=android-21",
                    "APP_STL=c++_shared",
                    "NDK_TOOLCHAIN_VERSION=clang",
                    "GENERATED_SRC_DIR=$buildDir/generated/source", // for react_codegen_* in this library's codegen/jni
                    "PROJECT_BUILD_DIR=${appProject.buildDir}", // for REACT_NDK_EXPORT_DIR in ReactAndroid's Android-prebuilt.mk
                    "REACT_ANDROID_DIR=${reactAndroidProject.projectDir}",
                    "REACT_ANDROID_BUILD_DIR=${reactAndroidProject.buildDir}",
                    "CODEGEN_MODULE_NAME=$codegenViewModuleName"
          cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
          cppFlags "-std=c++17"
          targets "${codegenViewModuleName}_registration"
        }
      }
    }
  }
  if (isNewArchitectureEnabled() && registrationCompat) {
    // We configure the NDK build only if you decide to opt-in for the New Architecture.
    externalNativeBuild {
      ndkBuild {
        path "Android.mk"
      }
    }
  }
  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 kotlin_version = getExtOrDefault("kotlinVersion")

dependencies {
  // For < 0.71, this will be from the local maven repo
  // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
  //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-native:+"
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

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