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

  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath 'com.android.tools.build:gradle:4.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'


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

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

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['PagerView_' + name]).toInteger()
}
def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')[0].toInteger()
def shouldUseNameSpace = agpVersion >= 8
def PACKAGE_PROP = "package=\"com.reactnativepagerview\""
def manifestOutFile = file("${projectDir}/src/main/AndroidManifest.xml")
def manifestContent = manifestOutFile.getText()
if(shouldUseNameSpace){
      manifestContent = manifestContent.replaceAll(
        PACKAGE_PROP,
        ''
    )  
} else {
    if(!manifestContent.contains("$PACKAGE_PROP")){
        manifestContent = manifestContent.replace(
            '<manifest',
            "<manifest $PACKAGE_PROP "
        )
    }
}
manifestContent.replaceAll("  ", " ")
manifestOutFile.write(manifestContent)

import groovy.json.JsonSlurper

// https://github.com/callstack/react-native-builder-bob/discussions/359
def registrationCompat = {
  def reactAndroidProject = rootProject.allprojects.find { it.name == 'ReactAndroid' }
  if (reactAndroidProject == null) return false

  def reactNativeManifest = file("${reactAndroidProject.projectDir}/../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.71
  // Use Android.mk for compatibility with react-native@0.68/0.69
  reactNativeVersion.matches('(0.68.*|0.69.*)')
}()

def codegenViewLibraryName = "RNCViewPager"
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') }

android {
  compileSdkVersion getExtOrIntegerDefault('compileSdkVersion')
  if (shouldUseNameSpace){
    namespace = "com.reactnativepagerview"
    buildFeatures {
      buildConfig true
    }
  }
  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/fabric/java",
            "${project.buildDir}/generated/source/codegen/java"
          ]
      } else {
          java.srcDirs += ["src/paper/java"]
      }
    }
  }
}

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 "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  implementation 'androidx.viewpager2:viewpager2:1.1.0'
}

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