/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

def latestSdkVersion = 34

buildscript {

    repositories {
        google()
        mavenCentral()
        maven { url "https://storage.googleapis.com/r8-releases/raw" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:8.1.1'
        classpath "com.vanniktech:gradle-maven-publish-plugin:${MAVEN_PUBLISH_PLUGIN}"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${KOTLIN_VERSION}"
        classpath "org.jetbrains.dokka:dokka-gradle-plugin:${DOKKA_VERSION}"
        classpath "com.facebook.kotlin.compilerplugins.dataclassgenerate:gradleplugin:${DATA_CLASS_GENERATE_VERSION}"
        classpath "com.android.tools:r8:8.5.35"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

apply plugin: 'com.vanniktech.maven.publish'

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }

    tasks.withType(Javadoc).all {
        options.addStringOption('Xdoclint:none', '-quiet')
    }
    // Disabled until there's a workaround/fix for https://github.com/Kotlin/dokka/issues/2472
    tasks.withType(com.android.build.gradle.tasks.JavaDocGenerationTask).all {
        enabled = false
    }
    configurations.all {
        // Temporarily exclude sample-barebones project from substitution in order to fix the gradle
        // build.
        if (project.name != "sample-barebones") {
            // These are to prevent upgrade problems where second-party dependencies like Fresco may be
            // depending on a specific, older version of Litho causing dex merging conflicts.
            resolutionStrategy.dependencySubstitution {
                substitute module('com.facebook.litho:litho-annotations') using project(':litho-annotations')
                substitute module('com.facebook.litho:litho-widget') using project(':litho-widget')
            }
        }
    }
}

subprojects {
    tasks.withType(Javadoc).all {
        enabled = false
    }

    tasks.withType(org.jetbrains.dokka.gradle.DokkaTaskPartial).configureEach {
        dokkaSourceSets {
            configureEach {
                def module_docs_file = 'module-docs.md'
                if (file(module_docs_file).exists()) {
                    includes.from(module_docs_file)
                }
            }
        }
        dependsOn(tasks.withType(org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask))
    }

    tasks.withType(Test) {
        systemProperty "robolectric.looperMode", "LEGACY"

        testLogging {
            exceptionFormat = 'full'
            showStackTraces = true
        }
    }

    plugins.withType(org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin) {
        kotlin {
            jvmToolchain(17)
        }
    }

    afterEvaluate {
        tasks.withType(Test) {
            it.dependsOn copyYogaLibs
            systemProperty 'java.library.path', "${rootDir}/build/jniLibs"
            environment 'LD_LIBRARY_PATH', "${rootDir}/build/jniLibs"
            environment 'DYLD_LIBRARY_PATH', "${rootDir}/build/jniLibs"

            def offlineDepsDir = System.getProperty('robolectric.dependency.dir')
            if (offlineDepsDir != null) {
                systemProperty 'robolectric.dependency.dir', "${rootDir}/$offlineDepsDir"
            }
        }
    }
}

apply plugin: 'org.jetbrains.dokka'

tasks.withType(org.jetbrains.dokka.gradle.DokkaMultiModuleTask).configureEach {
    outputDirectory = file("${rootDir}/website/static/reference")
    moduleName = "Litho"
}

project.gradle.startParameter.excludedTaskNames.add('testReleaseUnitTest')

ext {
    minSdkVersion = 24
    targetSdkVersion = latestSdkVersion
    compileSdkVersion = latestSdkVersion
    buildToolsVersion = '34.0.0'
    sourceCompatibilityVersion = JavaVersion.VERSION_17
    targetCompatibilityVersion = JavaVersion.VERSION_17
}

ext.forceReleaseBuild = project.hasProperty('forceReleaseBuild')
ext.isRelease = { forceReleaseBuild ||
        ['publish', 'publishToMavenLocal', 'publishToMavenCentral', 'publishAndReleaseToMavenCentral'].any { gradle.startParameter.taskNames.contains(it) } }
ext.isSnapshot = { VERSION_NAME.endsWith('-SNAPSHOT') }
ext.isDokkaBuild = getGradle().getStartParameter().getTaskNames().toString().toLowerCase().contains("dokka")

ext.deps = [
        // Android support
        supportAnnotations : 'androidx.annotation:annotation:1.0.0',
        supportAppCompat   : 'androidx.appcompat:appcompat:1.6.1',
        supportCollection  : 'androidx.collection:collection:1.4.0',
        supportCore        : 'androidx.core:core-ktx:1.13.1',
        supportFragment    : 'androidx.fragment:fragment:1.3.5',
        supportCustomView  : 'androidx.customview:customview:1.0.0',
        supportRecyclerView: 'androidx.recyclerview:recyclerview:1.2.0-beta01',
        supportEspresso    : 'androidx.test.espresso:espresso-core:3.1.1',
        supportEspressoIntents : 'androidx.test.espresso:espresso-intents:3.1.1',
        supportTestCore    : 'androidx.test:core:1.4.0',
        supportTestRunner  : 'androidx.test:runner:1.1.1',
        supportTestRules   : 'androidx.test:rules:1.1.1',
        supportTestJunit   : 'androidx.test.ext:junit:1.1.2',
        supportViewPager   : 'androidx.viewpager:viewpager:1.0.0',
        supportViewPager2  : 'androidx.viewpager2:viewpager2:1.1.0',
        supportMaterial    : 'com.google.android.material:material:1.2.0',
        supportTransition  : 'androidx.transition:transition:1.0.0',
        supportSwipeRefresh: 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0',
        supportDynamicAnimations : 'androidx.dynamicanimation:dynamicanimation-ktx:1.0.0-alpha03',
        // lifecycle
        lifecycle      : 'androidx.lifecycle:lifecycle-runtime:2.6.1',
        lifecycleKtx       : 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.1',
        viewModel      : 'androidx.lifecycle:lifecycle-viewmodel:2.3.1',
        liveData           : 'androidx.lifecycle:lifecycle-livedata:2.6.1',
        lifecycleService   : 'androidx.lifecycle:lifecycle-service:2.6.1',
        // First-party
        fresco             : 'com.facebook.fresco:fresco:3.0.0',
        frescoVito         : 'com.facebook.fresco:vito:3.0.0',
        frescoVitoLitho    : 'com.facebook.fresco:vito-litho:3.0.0',
        frescoVitoOptions  : 'com.facebook.fresco:vito-options:3.0.0',
        frescoVitoSource   : 'com.facebook.fresco:vito-source:3.0.0',
        soloader           : 'com.facebook.soloader:soloader:0.10.5',
        textlayoutbuilder  : 'com.facebook.fbui.textlayoutbuilder:textlayoutbuilder:1.7.0',
        screenshot         : 'com.facebook.testing.screenshot:core:0.5.0',
        flipper            : 'com.facebook.flipper:flipper:0.258.0',
        flipperLithoPlugin : 'com.facebook.flipper:flipper-litho-plugin:0.258.0',
        // Annotations
        jsr305             : 'com.google.code.findbugs:jsr305:3.0.1',
        inferAnnotations   : 'com.facebook.infer.annotation:infer-annotation:0.18.0',
        // Debugging and testing
        guava              : 'com.google.guava:guava:27.0.1-android',
        robolectric        : 'org.robolectric:robolectric:4.11.1',
        junit              : 'junit:junit:4.12',
        hamcrestLibrary    : 'org.hamcrest:hamcrest-library:1.3',
        mockitoCore        : 'org.mockito:mockito-core:4.11.0',
        assertjCore        : 'org.assertj:assertj-core:2.9.0',
        compileTesting     : 'com.google.testing.compile:compile-testing:0.14',
        mockitokotlin      : 'org.mockito.kotlin:mockito-kotlin:4.1.0',
        // Proguard annotations (published through Yoga)
        proguardAnnotations: 'com.facebook.yoga:proguard-annotations:1.14.1',
        // Processor
        javapoet           : 'com.squareup:javapoet:1.13.0',
        // Misc
        khronos            : 'org.khronos:opengl-api:gl1.1-android-2.1_r1',
        // Kotlin
        kotlinStandardLib  : "org.jetbrains.kotlin:kotlin-stdlib:${KOTLIN_VERSION}",
        kotlinCoroutines   : "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4",
        kotlinCoroutinesTest  : "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4",
        kotlinReflect      : "org.jetbrains.kotlin:kotlin-reflect:${KOTLIN_VERSION}"
]

// For releases, we want to depend on a stable version of Yoga.
ext.deps.yoga =
    isSnapshot()
        ? 'com.facebook.yoga:yoga:2.0.1' // can be a '-SNAPSHOT' release
        : 'com.facebook.yoga:yoga:2.0.1'

// This should hopefully only serve as a temporary measure until
// we have a proper Gradle setup for Yoga and JNI.
task copyYogaLibs(type: Copy, dependsOn: ':yoga:buckBuild') {
    from 'buck-out/gen/lib/yogajni/jni#default,shared/'
    include '*.so'
    include '*.dylib'
    include '*.dll'
    into "$buildDir/jniLibs"
    doLast {
        def yoga_deps = "find ${rootDir}/build/jniLibs".execute().text.trim()
        System.out.println("[Yoga Buck Build]: copied files:\n${yoga_deps}")
    }
}
