buildscript {
  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.1"
  }
}

task prepareKotlinBuildScriptModel {
  // This task is run during Gradle Sync in Android Studio.
}

def reactNativeArchitectures() {
  def value = project.getProperties().get("reactNativeArchitectures")
  return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

apply plugin: "com.android.library"
apply plugin: "com.facebook.react"

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

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

def safeAppExtGet(prop, fallback) {
  def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }
  appProject?.ext?.has(prop) ? appProject.ext.get(prop) : fallback
}

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
  return (major == 7 && minor >= 3) || major >= 8
}

def resolveReactNativeDirectory() {
  def reactNativeLocation = safeAppExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
  if (reactNativeLocation != null) {
    return file(reactNativeLocation)
  }

  // Fallback to node resolver for custom directory structures like monorepos.
  def reactNativePackage = file(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim())
  if (reactNativePackage.exists()) {
    return reactNativePackage.parentFile
  }

  throw new GradleException("[react-native-live-markdown] Unable to resolve react-native location in node_modules. Your app should define `REACT_NATIVE_NODE_MODULES_DIR` extension property in `app/build.gradle` with a path to react-native in node_modules.")
}

def getReactNativeMinorVersion() {
  def reactNativeRootDir = resolveReactNativeDirectory()
  def reactNativeProperties = new Properties()
  file("$reactNativeRootDir/ReactAndroid/gradle.properties").withInputStream { reactNativeProperties.load(it) }
  def reactNativeVersion = reactNativeProperties.getProperty("VERSION_NAME")
  return reactNativeVersion.split("\\.")[1].toInteger()
}

def REACT_NATIVE_MINOR_VERSION = getReactNativeMinorVersion()

android {
  if (supportsNamespace()) {
    namespace "com.expensify.livemarkdown"

    sourceSets {
      main {
        manifest.srcFile "src/main/AndroidManifestNew.xml"
      }
    }
  }

  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")

    buildConfigField "int", "REACT_NATIVE_MINOR_VERSION", REACT_NATIVE_MINOR_VERSION.toString()

    consumerProguardFiles "proguard-rules.pro"

    externalNativeBuild {
      cmake {
        arguments "-DANDROID_STL=c++_shared",
          "-DANDROID_TOOLCHAIN=clang",
          "-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}",
          "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
        abiFilters (*reactNativeArchitectures())
      }
    }
  }

  buildFeatures {
    buildConfig true
    prefab true
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  sourceSets {
    main {
      java.srcDirs += [
        // This is needed to build Kotlin project with NewArch enabled
        "${project.buildDir}/generated/source/codegen/java"
      ]

      // TextLayoutManager
      if (REACT_NATIVE_MINOR_VERSION <= 79) {
          java.srcDirs += "src/reactNativeVersionPatch/CustomMountingManager/79"
      } else if (REACT_NATIVE_MINOR_VERSION == 80) {
          java.srcDirs += "src/reactNativeVersionPatch/CustomMountingManager/80"
      } else {
          java.srcDirs += "src/reactNativeVersionPatch/CustomMountingManager/latest"
      }
    }
  }

  externalNativeBuild {
    cmake {
      path file('src/main/cpp/CMakeLists.txt')
      version '3.22.1'
    }
  }

  packagingOptions {
    doNotStrip '**/**/*.so'
    // For some reason gradle only complains about the duplicated version of librrc_root and libreact_render libraries
    // while there are more libraries copied in intermediates folder of the lib build directory, we exclude
    // only the ones that make the build fail (ideally we should only include libreanimated but we
    // are only allowed to specify exclude patterns)
    excludes = [
      "META-INF",
      "META-INF/**",
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libjsi.so",
      "**/libreactnativejni.so",
      "**/libreactnative.so",
      "**/libreact_nativemodule_core.so",
      "**/libruntimeexecutor.so",
      "**/libworklets.so",
      "**/libreact_render*.so",
      "**/librrc_root.so",
    ]
  }
}

repositories {
  mavenCentral()
  google()
}


dependencies {
  implementation "com.facebook.react:react-android" // version substituted by RNGP
  implementation "com.facebook.react:hermes-android" // version substituted by RNGP
  implementation project(":react-native-reanimated")
}

// This fixes linking errors due to undefined symbols from libworklets.so.
// During Gradle Sync, Android Gradle Plugin runs Prefab and treats worklets
// like a header-only library. During build, config files are not regenerated
// because the cache key does not change and AGP thinks that they are up-to-date.
afterEvaluate {
  prepareKotlinBuildScriptModel.dependsOn(":react-native-reanimated:prefabDebugPackage")
  prepareKotlinBuildScriptModel.dependsOn(":react-native-reanimated:prefabReleasePackage")
}
