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['Readium_kotlinVersion']
  ext.readium_version = '3.1.0'

  repositories {
    google()
    mavenCentral()
  }

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

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

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

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

android {
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')
  namespace "com.reactnativereadium"
  defaultConfig {
    minSdkVersion 24
    targetSdkVersion getExtOrIntegerDefault('targetSdkVersion')
    versionCode 1
    versionName "1.0"

    externalNativeBuild {
      cmake {
        cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
        arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
        abiFilters "x86", "x86_64", "armeabi-v7a", "arm64-v8a"
      }
    }
  }

  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }
  lint {
    disable 'GradleCompatible'
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
  }
  kotlinOptions {
    jvmTarget = "17"
  }

  buildFeatures {
    viewBinding true
    prefab true
  }

  sourceSets {
    main {
      java.srcDirs += ["${project.projectDir}/../nitrogen/generated/android/kotlin"]
    }
  }
}

repositories {
  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 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."
    )
  }
}

def kotlin_version = getExtOrDefault('kotlinVersion')

dependencies {
  // noinspection GradleDynamicVersion
  api "com.facebook.react:react-native:+"
  implementation project(':react-native-nitro-modules')
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

  // readium deps
  implementation "org.readium.kotlin-toolkit:readium-shared:$readium_version"
  implementation "org.readium.kotlin-toolkit:readium-streamer:$readium_version"
  implementation ("org.readium.kotlin-toolkit:readium-navigator:$readium_version") {
    // this package doesn't provide audio playback, so remove exoplayer
    // transitive deps to avoid potential collisions with other projects.
    exclude group: "com.google.android.exoplayer"
  }

  // other deps
  implementation "androidx.core:core-ktx:1.13.1"
  implementation "androidx.activity:activity-ktx:1.9.0"
  implementation "androidx.appcompat:appcompat:1.6.1"
  implementation "androidx.browser:browser:1.7.0"
  implementation "androidx.cardview:cardview:1.0.0"
  implementation "androidx.constraintlayout:constraintlayout:2.1.4"
  implementation "androidx.fragment:fragment-ktx:1.7.1"
  implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.8.4"
  implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.4"
  implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.4"
  implementation 'androidx.navigation:navigation-fragment-ktx:2.7.7'
  implementation 'androidx.navigation:navigation-ui-ktx:2.7.7'
  implementation "androidx.paging:paging-runtime-ktx:3.2.1"
  implementation "androidx.recyclerview:recyclerview:1.3.2"
  implementation "androidx.viewpager2:viewpager2:1.1.0"
  implementation "androidx.webkit:webkit:1.8.0"
  implementation "com.google.android.material:material:1.11.0"
  implementation "com.jakewharton.timber:timber:5.0.1"
  // AM NOTE: needs to stay this version for now (June 24,2020)
  //noinspection GradleDependency
  implementation "com.squareup.picasso:picasso:2.71828"
  implementation "joda-time:joda-time:2.10.13"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0"

  implementation "org.jsoup:jsoup:1.18.3"

  // Room database
  final roomVersion = "2.6.1"
  implementation "androidx.room:room-runtime:$roomVersion"
  implementation "androidx.room:room-ktx:$roomVersion"
  annotationProcessor "androidx.room:room-compiler:$roomVersion"

  implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
  //noinspection LifecycleAnnotationProcessorWithJava8
  annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.8.4"

  testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
  testImplementation "junit:junit:4.13.2"

  androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1"
  androidTestImplementation "androidx.test:runner:1.5.2"
}
