buildscript {
    apply(from: {
        def searchDir = rootDir.toPath()
        do {
            def p = searchDir.resolve("node_modules/react-native-test-app/android/dependencies.gradle")
            if (p.toFile().exists()) {
                return p.toRealPath().toString()
            }
        } while (searchDir = searchDir.getParent())
        throw new GradleException("Could not find `react-native-test-app`");
    }())

    repositories {
        mavenCentral()
        google()
    }

    dependencies {
        getReactNativeDependencies().each { dependency ->
            classpath(dependency)
        }
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url({
                def searchDir = rootDir.toPath()
                do {
                    def p = searchDir.resolve("node_modules/react-native/android")
                    if (p.toFile().exists()) {
                        return p.toRealPath().toString()
                    }
                } while (searchDir = searchDir.getParent())
                throw new GradleException("Could not find `react-native`");
            }())
        }
        mavenCentral()
        google()
        // START:detox
        maven {
          url("$rootDir/../node_modules/detox/Detox-android")
        }
        // END:detox
    }
    
    // START:detox
    afterEvaluate { project ->
        def androidExtension = project.extensions.findByName('android')
        if (androidExtension != null && project.name == 'app') {
            androidExtension.testBuildType System.getProperty('testBuildType', 'debug')
            androidExtension.defaultConfig {
                testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'

                ndk {
                    abiFilters 'arm64-v8a', 'x86', 'x86_64'
                }
            }

            androidExtension.buildTypes {
                release {
                    proguardFile "${rootProject.projectDir}/../node_modules/detox/android/detox/proguard-rules-app.pro"
                }
            }

            androidExtension.sourceSets.androidTest.java.srcDirs += "$rootDir/app/src/androidTest/java"

            project.dependencies {
                if (reactNativeVersion > 0 && reactNativeVersion < v(0, 73, 0)) {
                    androidTestImplementation('com.wix:detox-legacy:+')
                } else {
                    androidTestImplementation('com.wix:detox:+')
                }
                implementation 'androidx.appcompat:appcompat:1.1.0'
            }
        }
    }
    // END:detox
}
