import org.jetbrains.kotlin.gradle.dsl.JvmTarget

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['OlopaysdkReactNative_kotlinVersion']

  repositories {
    google()
    mavenCentral()

    // Add this to find the React Native Gradle Plugin locally
    maven { url(new File(rootDir, "../node_modules/react-native/android")) }
  }

  dependencies {
    classpath 'com.android.tools.build:gradle:8.13.0'
    // noinspection DifferentKotlinGradleVersion
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    if (project == rootProject) {
      // This allows the standalone build to find the 'com.facebook.react' plugin class
      classpath "com.facebook.react:react-native-gradle-plugin"
    }
  }
}

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'com.facebook.react'
apply from: 'load-local-dev-repo-settings.gradle'

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

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

android {
  if (project.android.hasProperty("namespace")) {
    namespace 'com.olopaysdkreactnative'
  }
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')

  buildFeatures {
    buildConfig = true
  }

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault('minSdkVersion')
    targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", "true"

    if (!project.hasProperty('OlopaysdkReactNative_minSdkVersion')) {
      minSdkVersion 24
    }
    if (!project.hasProperty('OlopaysdkReactNative_targetSdkVersion')) {
      targetSdkVersion 36
    }
    if (!project.hasProperty('OlopaysdkReactNative_compileSdkVersion')) {
      compileSdkVersion 36
    }
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
  }

  lintOptions {
    disable 'GradleCompatible'
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
  }

  kotlin {
    compilerOptions {
      jvmTarget.set(JvmTarget.JVM_17)

      freeCompilerArgs.addAll([
              "-Xcontext-receivers",
              "-Xopt-in=kotlin.RequiresOptIn"
      ])
    }
  }

  packagingOptions {
    pickFirst '**/libc++_shared.so'
    pickFirst '**/libjsc.so'
    pickFirst '**/libfbjni.so'
    pickFirst '**/libfolly_runtime.so'
    pickFirst '**/libglog.so'
    pickFirst '**/libjsi.so'
    pickFirst '**/libreactnativejni.so'
    pickFirst '**/libyoga.so'
  }
}

repositories {
  mavenCentral()
  google()
  rootProject.ext.addLocalDevRepo(repositories)

  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 GradleException(
      "${project.name}: unable to locate React Native android sources. " +
      "Ensure you have you installed React Native as a dependency in your project and try again."
    )
  }
}

dependencies {
  if (!rootProject.ext.addLocalDevDependency(dependencies)) {
    implementation "com.olo.olopay:olo-pay-android-sdk:5.0.0"
  }

  implementation "androidx.constraintlayout:constraintlayout:2.2.1"
  implementation "androidx.core:core-ktx:1.17.0"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2"

  // noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-android:+"
  implementation "com.google.android.material:material:1.13.0"
}

react {
  if (rootProject.ext.has('nodeDir') && rootProject.ext.nodeDir) {
    println "======================================"
    println "Using Local Node Override"
    println "${rootProject.ext.nodeDir}"
    println "======================================"

    nodeExecutableAndArgs = [rootProject.ext.nodeDir]
  }

  jsRootDir = file("../src/")
  libraryName = "OlopaysdkReactNative"
  codegenJavaPackageName = "com.olopaysdkreactnative"
}