import com.android.builder.model.ProductFlavor

import java.util.regex.Pattern

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'io.sentry.android.gradle'

buildscript {

  repositories {
    maven {
      url "https://maven.google.com"
    }
  }
}

android {

  kotlinOptions {
    jvmTarget = "1.8"
  }

  // Websockets
  useLibrary 'org.apache.http.legacy'

  compileSdkVersion Integer.parseInt(project.COMPILE_SDK_VERSION)
  buildToolsVersion BUILD_TOOLS_VERSION

  // keep the "applicationId" var in third place for the jenkins build script hack
  defaultConfig {
    minSdkVersion project.MINIMUM_SDK_VERSION
    targetSdkVersion Integer.parseInt(project.TARGET_SDK_VERSION)
    multiDexEnabled true
    applicationId "cm.aptoide.pt"
    versionCode project.VERSION_CODE_VANILLA_PROD.toInteger()
    versionName project.VERSION_NAME_VANILLA
    testProguardFile 'proguard-rules-test.pro'
    testInstrumentationRunner "cm.aptoide.pt.MultidexAndroidJunitRunner"
    // vectorDrawables.useSupportLibrary = true
    manifestPlaceholders = [dataPlaceholder: generateData()]
  }

  lintOptions {
    disable 'UseSparseArrays'
    abortOnError false
  }

  signingConfigs {
    debug {
      v2SigningEnabled = false
    }
    release {
      storeFile = file(project.STORE_FILE_VANILLA)
      storePassword = project.STORE_PASSWORD_VANILLA
      keyAlias = project.KEY_ALIAS_VANILLA
      keyPassword = project.KEY_PASSWORD_VANILLA
      v2SigningEnabled = false
    }
  }

  testOptions {
    unitTests.all {
      testLogging {
        events "passed", "skipped", "failed", "standardOut", "standardError"
        outputs.upToDateWhen { false }
        showStandardStreams = true
      }
    }
  }

  flavorDimensions "product", "mode"
  productFlavors {
    cobrand {
      dimension "product"
      applicationId "com.aptoide.partners." + project.COBRAND_APPLICATION_ID_SUFFIX.toString()
      versionNameSuffix ".c" + project.COBRAND_VERSION.toString()
      matchingFallbacks = ['internal', 'prod']
    }

    vanilla {
      dimension "product"
      applicationId defaultConfig.getApplicationId()
      matchingFallbacks = ['internal', 'prod']
    }

    internal {
      dimension "mode"
      applicationIdSuffix "internal"
      versionName defaultConfig.getVersionName() + "." + getDate()
      versionCode project.VERSION_CODE_VANILLA_INTERNAL.toInteger()
      matchingFallbacks = ['internal', 'prod']
    }

    dev {
      dimension "mode"
      applicationIdSuffix "dev"
      versionName defaultConfig.getVersionName() + "." + getDate()
      versionCode project.VERSION_CODE_VANILLA_DEV.toInteger()
      matchingFallbacks = ['prod', 'internal']
    }

    prod {
      dimension "mode"
    }

    leak {
      dimension "mode"
      applicationIdSuffix ".leak"
      matchingFallbacks = ['internal', 'prod']
    }
  }

  buildTypes {
    debug {
      testCoverageEnabled = false
      buildConfigField "boolean", "CRASH_REPORTS_DISABLED", "true"
      zipAlignEnabled false
      minifyEnabled false
      shrinkResources false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules-debug.pro'
      matchingFallbacks = ['release']
    }

    release {
      buildConfigField "boolean", "CRASH_REPORTS_DISABLED", "false"
      zipAlignEnabled true
      minifyEnabled true
      shrinkResources true
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      signingConfig signingConfigs.release
    }
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  variantFilter { variant ->
    def names = variant.flavors*.name

    if (names.contains('cobrand') && (names.contains('internal') || names.contains('leak'))) {
      setIgnore(true)
    }
  }

  packagingOptions {
    exclude 'META-INF/services/javax.annotation.processing.Processor'
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/MANIFEST.MF'
    exclude 'META-INF/LGPL2.1'
    exclude 'META-INF/rxjava.properties'
    exclude 'version.properties'
  }

  testOptions {
    unitTests.returnDefaultValues = true
  }

  applicationVariants.all { variant ->

    List<ProductFlavor> flavors = variant.getProductFlavors()
    String applicationIdBase = flavors[0].applicationId
    String applicationIdSuffix = flavors[1].applicationIdSuffix
    String applicationId = applicationIdBase

    def searchSuggestionProviderAuthority =
        "${applicationIdBase}.provider.SearchSuggestionProvider"
    def storeSuggestionProviderAuthority =
        "${applicationIdBase}.provider.StoreSearchSuggestionProvider"
    def toolboxProviderAuthority = "${applicationIdBase}.StubProvider"

    if (applicationIdSuffix != null) {
      searchSuggestionProviderAuthority += ".${applicationIdSuffix}"
      storeSuggestionProviderAuthority += ".${applicationIdSuffix}"
      toolboxProviderAuthority += ".${applicationIdSuffix}"
      applicationId += ".${applicationIdSuffix}"
    }

    variant.mergedFlavor.manifestPlaceholders =
        [toolboxProviderAuthority        : "${toolboxProviderAuthority}",
         suggestionProviderAuthority     : "${searchSuggestionProviderAuthority}",
         storeSuggestionProviderAuthority: "${storeSuggestionProviderAuthority}",
         appLovinApiKey                  : "${project.MOPUB_APPLOVIN_SDK_KEY}",
         adMobApiKey                     : "${project.AD_MOB_APPLICATION_ID}",
         dataPlaceholder                 : generateData()]

    variant.resValue "string", "authenticator_account_type", applicationId
    variant.resValue "string", "search_suggestion_provider_authority",
        searchSuggestionProviderAuthority
    variant.resValue "string", "store_suggestion_provider_authority",
        storeSuggestionProviderAuthority

    variant.buildConfigField "String", "CONTENT_AUTHORITY", "\"" + toolboxProviderAuthority + "\""
    variant.buildConfigField "String", "SIGNATURE_BACKUP", "\"" + project.SIGNATURE_BACKUP + "\""
    variant.buildConfigField "String", "SIGNATURE_UPLOADER",
        "\"" + project.SIGNATURE_UPLOADER + "\""
    variant.buildConfigField "String", "GMS_SERVER_ID", "\"" + project.GMS_SERVER_ID_VANILLA + "\""
    variant.buildConfigField "int", "CAMPAIGN_NOTIFICATION_SYNC_INTERVAL_MILLIS",
        project.CAMPAIGN_NOTIFICATION_SYNC_INTERVAL_MILLIS
    variant.buildConfigField "int", "ANALYTICS_EVENTS_INITIAL_DELAY_IN_MILLIS",
        project.ANALYTICS_EVENTS_INITIAL_DELAY_IN_MILLIS
    variant.buildConfigField "int", "ANALYTICS_EVENTS_TIME_INTERVAL_IN_MILLIS",
        project.ANALYTICS_EVENTS_TIME_INTERVAL_IN_MILLIS
    variant.buildConfigField "long", "ANALYTICS_SESSION_INTERVAL_IN_MILLIS",
        project.ANALYTICS_SESSION_INTERVAL_IN_MILLIS
    variant.buildConfigField "String", "APTOIDE_WEB_SERVICES_APICHAIN_BDS_HOST",
        "\"" + project.APTOIDE_WEB_SERVICES_APICHAIN_BDS_HOST + "\""
    variant.buildConfigField "String", "HOME_PROMOTION_ID",
        "\"" + project.HOME_PROMOTION_ID + "\""
    variant.buildConfigField "String", "COBRAND_APPLICATION_ID_SUFFIX",
        "\"" + project.COBRAND_APPLICATION_ID_SUFFIX + "\""
    variant.buildConfigField "String", "APPLOVIN_SDK_VERSION",
        "\"" + APPLOVIN_SDK_VERSION + "\""
    variant.buildConfigField "String", "APPLOVIN_ADAPTER_VERSION",
        "\"" + MOPUB_MEDIATION_APPLOVIN_VERSION + "\""
    variant.buildConfigField "String", "APPNEXT_SDK_VERSION",
        "\"" + APPNEXT_SDK_VERSION + "\""

    variant.buildConfigField "int", "ROOM_SCHEMA_VERSION",
        project.ROOM_SCHEMA_VERSION
    variant.buildConfigField "String", "ROOM_DATABASE_NAME",
        "\"" + project.ROOM_DATABASE_NAME + "\""

    variant.buildConfigField "int", "INSTALLING_STATE_INSTALLER_TIMEOUT_IN_MILLIS_21_PLUS",
        project.INSTALLING_STATE_INSTALLER_TIMEOUT_IN_MILLIS_HIGHER_EQ_21_OS
    variant.buildConfigField "int", "INSTALLING_STATE_INSTALLER_TIMEOUT_IN_MILLIS_21_MINUS",
        project.INSTALLING_STATE_INSTALLER_TIMEOUT_IN_MILLIS_BELOW_21_OS
    variant.buildConfigField "int", "ROOT_TIMEOUT",
        project.ROOT_TIMEOUT_IN_MILLIS

    if (flavors[0].name.contains("cobrand")) {
      variant.buildConfigField "String", "APTOIDE_THEME", "\"" + project.COBRAND_THEME + "\""
      variant.resValue "string", "facebook_app_id", "\"" + project.FACEBOOK_APP_ID_COBRAND + "\""
      resValue "string", "fb_login_protocol_scheme",
          "\"" + "fb" + project.FACEBOOK_APP_ID_COBRAND + "\""
      variant.buildConfigField "String", "MARKET_NAME", "\"" + project.COBRAND_MARKET_NAME + "\""
      variant.buildConfigField "String", "COBRAND_OEMID", "\"" + project.COBRAND_OEMID + "\""
      if (flavors[1].name.contains("dev")) {
        variant.resValue "string", "COBRAND_LOGO_TITLE",
            "\"" + project.COBRAND_MARKET_NAME + "\"" + " Dev"
      } else {
        variant.resValue "string", "COBRAND_LOGO_TITLE", "\"" + project.COBRAND_MARKET_NAME + "\""
      }
    } else {
      //vanilla
      variant.resValue "string", "facebook_app_id", "\"" + project.FACEBOOK_APP_ID_VANILLA + "\""
      resValue "string", "fb_login_protocol_scheme",
          "\"" + "fb" + project.FACEBOOK_APP_ID_VANILLA + "\""
      variant.buildConfigField "String", "APTOIDE_THEME", "\"" + "default" + "\""
      variant.buildConfigField "String", "MARKET_NAME", "\"" + "Aptoide" + "\""
    }

    //flurry
    def type = variant.variantData.variantConfiguration.buildType.name

    if (flavors[1].name.contains('prod') && type == 'release') {
      if (flavors[0].name.contains('cobrand')) {
        buildConfigField "String", "FLURRY_KEY", "\"" + project.FLURRY_CO_BRAND_KEY + "\""
      } else {
        buildConfigField "String", "FLURRY_KEY", "\"" + project.FLURRY_KEY + "\""
      }
    } else {
      buildConfigField "String", "FLURRY_KEY", "\"" + project.FLURRY_DEBUG_KEY + "\""
    }

    variant.buildConfigField "String", "MOPUB_VUNGLE_APPLICATION_ID",
        "\"" + project.MOPUB_VUNGLE_APPLICATION_ID + "\""
    variant.buildConfigField "String", "MOPUB_UNITYADS_GAME_ID",
        "\"" + project.MOPUB_UNITYADS_GAME_ID + "\""
    variant.buildConfigField "String", "MOPUB_INMOBI_ACCOUNT_ID",
        "\"" + project.MOPUB_INMOBI_ACCOUNT_ID + "\""
    variant.buildConfigField "String", "MOPUB_FYBER_APPLICATION_ID",
        "\"" + project.MOPUB_FYBER_APPLICATION_ID + "\""
    variant.buildConfigField "String", "MOPUB_FYBER_INTERSTITIAL_SPOT_ID",
        "\"" + project.MOPUB_FYBER_INTERSTITIAL_SPOT_ID + "\""
    variant.buildConfigField "String", "MOPUB_FYBER_BANNER_SPOT_ID",
        "\"" + project.MOPUB_FYBER_BANNER_SPOT_ID + "\""

    variant.buildConfigField "String", "MOPUB_VIDEO_APPVIEW_PLACEMENT_ID",
        "\"" + project.MOPUB_VIDEO_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_NATIVE_APPVIEW_PLACEMENT_ID",
        "\"" + project.MOPUB_NATIVE_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_NATIVE_HOME_PLACEMENT_ID",
        "\"" + project.MOPUB_NATIVE_HOME_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_NATIVE_SEARCH_V3_PLACEMENT_ID",
        "\"" + project.MOPUB_NATIVE_SEARCH_V3_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_BANNER_50_APPVIEW_PLACEMENT_ID",
        "\"" + project.MOPUB_BANNER_50_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_BANNER_50_SEARCH_V2_PLACEMENT_ID",
        "\"" + project.MOPUB_BANNER_50_SEARCH_V2_PLACEMENT_ID_PROD + "\""
    variant.buildConfigField "String", "MOPUB_BANNER_50_HOME_PLACEMENT_ID",
        "\"" + project.MOPUB_BANNER_50_PLACEMENT_ID_PROD + "\""

    variant.buildConfigField "String", "MOPUB_VIDEO_EXCLUSIVE_PLACEMENT_ID",
        "\"" + project.MOPUB_VIDEO_EXCLUSIVE_PLACEMENT_ID + "\""
    variant.buildConfigField "String", "MOPUB_BANNER_50_EXCLUSIVE_PLACEMENT_ID",
        "\"" + project.MOPUB_BANNER_50_EXCLUSIVE_PLACEMENT_ID + "\""
    variant.buildConfigField "String", "MOPUB_NATIVE_EXCLUSIVE_PLACEMENT_ID",
        "\"" + project.MOPUB_NATIVE_EXCLUSIVE_PLACEMENT_ID + "\""

    variant.buildConfigField "String", "RAKAM_API_KEY",
        "\"" + project.RAKAM_API_KEY_TEST + "\""

    //Sentry
    if (flavors[0].name.contains("vanilla") && flavors[1].name.contains('prod') &&
        type ==
        'release') {
      buildConfigField "String", "SENTRY_API_KEY", "\"" + project.SENTRY_API_KEY + "\""
      buildConfigField "String", "SENTRY_DSN_KEY", "\"" + project.SENTRY_DSN_KEY + "\""
    } else if (flavors[0].name.contains("cobrand")) {
      buildConfigField "String", "SENTRY_API_KEY", "\"" + project.SENTRY_API_KEY_COBRAND + "\""
      buildConfigField "String", "SENTRY_DSN_KEY", "\"" + project.SENTRY_DSN_KEY_COBRAND + "\""
    } else {
      buildConfigField "String", "SENTRY_API_KEY", "\"" + project.SENTRY_API_KEY_DEBUG + "\""
      buildConfigField "String", "SENTRY_DSN_KEY", "\"" + project.SENTRY_DSN_KEY_DEBUG + "\""
    }

    variant.outputs.all { output ->
      def SEP = "_"
      def dimension = variant.productFlavors[0].name
      def flavor = variant.productFlavors[1].name
      def buildType = variant.variantData.variantConfiguration.buildType.name
      def versionName = variant.versionName
      def versionCode = variant.versionCode

      def newApkName = dimension + SEP +
          flavor +
          SEP +
          buildType +
          SEP +
          versionName +
          SEP +
          versionCode +
          ".apk"

      outputFileName = newApkName
    }

    variant.outputs.each { output ->
      output.processManifest.doLast {

        def placeholders = variant.mergedFlavor.manifestPlaceholders
        if (placeholders == null || placeholders.isEmpty()) {
          return
        }

        File manifest = new File(manifestOutputDirectory.get().asFile, "AndroidManifest.xml")

        def manifestContent = manifest.getText()

        placeholders.each { key, value ->
          Pattern pattern = Pattern.compile(Pattern.quote("<!-- \${$key} -->"), Pattern.DOTALL)

          manifestContent = pattern.matcher(manifestContent).replaceAll(value)
        }

        manifest.write(manifestContent)
      }
    }
  }

  dexOptions {
    dexInProcess = project.APTOIDE_DEX_IN_PROCESS
    preDexLibraries = project.APTOIDE_PRE_DEX_LIBRARIES
    javaMaxHeapSize = project.APTOIDE_DEX_JAVA_MAX_HEAP_SIZE
  }
  sourceSets { release { java.srcDirs = ['src/release/java', 'src/release/java/'] } }
}

kapt {
  correctErrorTypes = true
}

dependencies {

  implementation project(path: ':crashreports')
  implementation project(path: ':downloadmanager')
  implementation project(path: ':aptoide-database')
  implementation project(path: ':aptoidepreferences')
  implementation project(path: ':aptoide-account-manager')
  implementation project(path: ':aptoide-analytics-core')
  implementation project(path: ':aptoide-analytics-default-implementation')
  implementation project(path: ':dataprovider')
  implementation project(path: ':utils')
  implementation project(path: ':packageinstaller')
  implementation project(path: ':aptoide-views')
  implementation project(path: ':appcoins')

  androidTestImplementation "io.reactivex:rxjava:${RXJAVA_VERSION}"
  implementation "io.reactivex:rxjava:${RXJAVA_VERSION}"
  implementation "com.squareup.retrofit2:adapter-rxjava:${RETROFIT_VERSION}"
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-rx2:${COROUTINES_VERSION}")

  implementation "androidx.multidex:multidex:${MULTIDEX_VERSION}"

  androidTestImplementation "androidx.multidex:multidex-instrumentation:${MULTIDEX_VERSION}"

  testImplementation "junit:junit:${JUNIT_VERSION}"
  testImplementation "org.mockito:mockito-core:${MOCKITO_CORE_VERSION}"
  // Force usage of support annotations in the test app, since it is internally used by the runner module.
  androidTestImplementation "junit:junit:${JUNIT_VERSION}"
  androidTestImplementation "androidx.test:runner:${RUNNER_VERSION}"
  androidTestImplementation "androidx.test:rules:${RULES_VERSION}"

  //dependencies needed for UITests
  androidTestImplementation "androidx.annotation:annotation:${ANDROIDX_ANNOTATION_VERSION}"
  androidTestImplementation "androidx.test.espresso:espresso-core:${ESPRESSO_VERSION}"
  androidTestImplementation "androidx.test.espresso:espresso-contrib:${ESPRESSO_VERSION}"
  androidTestImplementation "androidx.test.espresso:espresso-intents:${ESPRESSO_VERSION}"
  androidTestImplementation "androidx.recyclerview:recyclerview:${RECYCLER_VIEW_VERSION}"
  androidTestImplementation "com.jakewharton.rxrelay:rxrelay:${RX_RELAY}"
  androidTestImplementation "org.mockito:mockito-android:${MOCKITO_CORE_ANDROID_VERSION}"
  androidTestImplementation("com.squareup.okhttp3:okhttp:${OKHTTP_VERSION}") {
    force = true
  }
  androidTestImplementation "com.squareup.retrofit2:retrofit:${RETROFIT_VERSION}"

  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

  implementation "androidx.annotation:annotation:${ANDROIDX_ANNOTATION_VERSION}"

  implementation "com.fasterxml.jackson.core:jackson-databind:${JACKSON_VERSION}"

  implementation "androidx.appcompat:appcompat:${APPCOMPAT_VERSION}"
  implementation "androidx.recyclerview:recyclerview:${RECYCLER_VIEW_VERSION}"
  implementation "androidx.legacy:legacy-support-v13:${LEGACY_SUPPORT_VERSION}"
  implementation "androidx.cardview:cardview:${CARD_VIEW_VERSION}"
  implementation "androidx.browser:browser:${BROWSER_VERSION}"

  implementation "com.airbnb.android:epoxy:${EPOXY_VERSION}"
  kapt "com.airbnb.android:epoxy-processor:${EPOXY_VERSION}"

  //Color Palette
  implementation "androidx.palette:palette:${PALETTE_VERSION}"

  implementation "androidx.preference:preference:${PREFERENCES_VERSION}"

  implementation "androidx.constraintlayout:constraintlayout:${CONSTRAINT_LAYOUT_VERSION}"

  implementation "com.google.android.material:material:${MATERIAL_VERSION}"

  implementation "com.jpardogo.materialtabstrip:library:${MATERIAL_TAB_STRIP_VERSION}"

  implementation "com.trello:rxlifecycle:${TRELLO_RX_LIFECYCLE_VERSION}"
  // If you want pre-written Activities and Fragments you can subclass as providers
  implementation "com.trello:rxlifecycle-components:${TRELLO_RX_LIFECYCLE_VERSION}"
  implementation "com.jakewharton.rxrelay:rxrelay:${RX_RELAY}"

  implementation "androidx.lifecycle:lifecycle-process:${LIFECYCLE_VERSION}"

  implementation "cn.dreamtobe.filedownloader:filedownloader-okhttp3-connection:${FILE_DOWNLOADER_OKHTTP_IMP_VERSION}"

  implementation "com.jakewharton.rxbinding:rxbinding:${JW_RX_BINDING_VERSION}"
  implementation "com.jakewharton.rxbinding:rxbinding-design:${JW_RX_BINDING_VERSION}"
  implementation "com.jakewharton.rxbinding:rxbinding-support-v4:${JW_RX_BINDING_VERSION}"
  implementation "com.jakewharton.rxbinding:rxbinding-appcompat-v7:${JW_RX_BINDING_VERSION}"
  implementation "com.jakewharton.rxbinding:rxbinding-recyclerview-v7:${JW_RX_BINDING_VERSION}"
  implementation "com.google.code.gson:gson:${GSON_VERSION}"


  // Mopub
  implementation("com.mopub:mopub-sdk:${MOPUB_SDK_VERSION}@aar") {
    transitive = true
    exclude module: 'moat-mobile-app-kit'
    exclude group: "com.androidx"
  }

  // AppLovin
  implementation "com.applovin:applovin-sdk:${APPLOVIN_SDK_VERSION}"
  implementation "com.mopub.mediation:applovin:${MOPUB_MEDIATION_APPLOVIN_VERSION}"

  // Google (AdMob)
  implementation "com.mopub.mediation:admob:${MOPUB_MEDIATION_AD_MOB_SDK_VERSION}"

  // Vungle
  implementation("com.github.vungle:vungle-android-sdk:${VUNGLE_SDK_VERSION}") {
    transitive = true
  }
  implementation "com.mopub.mediation:vungle:${MOPUB_MEDIATION_VUNGLE_VERSION}"

  // UnityAds, Chartboost & One by AOL
  implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
  implementation "com.unity3d.ads:unity-ads:${UNITY_ADS_SDK_VERSION}"
  implementation "com.mopub.mediation:unityads:${MOPUB_MEDIATION_UNITYADS_VERSION}"

  //AppNext
  implementation "com.appnext.sdk.adapters:mopub-ads:${APPNEXT_SDK_VERSION}"
  implementation "com.appnext.sdk.adapters:mopub-native-ads:${APPNEXT_SDK_VERSION}"
  implementation "com.appnext.sdk.adapters:mopub-banners:${APPNEXT_SDK_VERSION}"

  //Inmobi
  implementation "com.inmobi.monetization:inmobi-ads:${INMOBI_SDK_VERSION}"
  implementation "com.squareup.picasso:picasso:${PICASSO_VERSION}"

  // Flurry Android sdk
  implementation "com.flurry.android:analytics:${FLURRY_VERSION}"

  //Rakam
  implementation "io.rakam:android-sdk:${RAKAM_VERSION}"

  //Sentry
  implementation "io.sentry:sentry-android:${SENTRY_VERSION}"

  // Remote install
  implementation 'org.slf4j:slf4j-simple:1.7.21'
  implementation 'org.slf4j:slf4j-api:1.7.21'
  implementation "org.jmdns:jmdns:${JMDNS_VERSION}"

  implementation("com.squareup.okhttp3:okhttp:${OKHTTP_VERSION}") {
    force = true
  }
  implementation("com.squareup.okhttp3:logging-interceptor:${OKHTTP_VERSION}") {
    force = true
  }

  // Parceler - https://github.com/johncarl81/parceler
  implementation "org.parceler:parceler-api:${PARCELER_VERSION}"
  kapt "org.parceler:parceler:${PARCELER_VERSION}"

  //noinspection GradleDependency
  implementation "com.google.android.gms:play-services-basement:${PLAY_SERVICES_BASEMENT_VERSION}"
  implementation "com.google.android.gms:play-services-location:${PLAY_SERVICES_LOCATION_VERSION}"
  //noinspection GradleDependency
  implementation "com.google.android.gms:play-services-auth:${PLAY_SERVICES_AUTH_VERSION}"
  implementation "com.google.android.gms:play-services-ads:${PLAY_SERVICES_ADS_VERSION}"
  implementation "com.google.android.gms:play-services-safetynet:${PLAY_SERVICES_SAFETYNET_VERSION}"


  // Facebook Core (Analytics)
  implementation "com.facebook.android:facebook-core:${FACEBOOK_ANDROID_SDK_VERSION}"

  // Facebook Login
  implementation "com.facebook.android:facebook-login:${FACEBOOK_ANDROID_SDK_VERSION}"

  leakImplementation "com.squareup.leakcanary:leakcanary-android:${LEAK_CANARY_VERSION}"

  implementation("com.github.bumptech.glide:glide:${GLIDE_VERSION}")

  kapt "com.github.bumptech.glide:compiler:${GLIDE_VERSION}"

  implementation "com.google.dagger:dagger:${DAGGER_VERSION}"

  kapt "com.google.dagger:dagger-compiler:${DAGGER_VERSION}"

  implementation("com.asfoundation:appcoins-contract-proxy:${APPC_CONTRACT_PROXY_VERSION}") {
    exclude group: 'org.web3j'
  }

  //careful updating this because of support library conflicts
  implementation "com.airbnb.android:lottie:${LOTTIE_VERSION}"

  // Room components
  implementation "androidx.room:room-runtime:${ROOM_VERSION}"
  annotationProcessor "androidx.room:room-compiler:${ROOM_VERSION}"
  androidTestImplementation "androidx.room:room-testing:${ROOM_VERSION}"

  // RxJava support for Room
  implementation "androidx.room:room-rxjava2:${ROOM_VERSION}"

  // Rxjava Interop
  implementation "com.github.akarnokd:rxjava2-interop:${RXJAVA2_INTEROP}"

  // Work Manager
  // Java
  implementation "androidx.work:work-runtime:2.1.0"
  // Kotlin + coroutines
  implementation "androidx.work:work-runtime-ktx:2.1.0"
}

String getDate() {
  def date = new Date()
  def formattedDate = date.format('yyyyMMdd')
  return formattedDate
}

static def generateData() {
  return data("app.aptoide.com") + data("market.android.com") +
      dataWithPathPrefix("webservices.aptoide.com", "/apkinstall") +
      data("play.google.com") +
      aptoideSubdomainDataWithWildCardPrefix() +
      aptoideSubdomainData("/store/..*") +
      aptoideSubdomainData("/thank-you*") +
      data("community.aptoide.com", "/using-appcoins*") +
      aptoideSubdomainData("/download*") +
      aptoideSubdomainData("/editorial/..*") +
      aptoideSubdomainData("/app") +
      aptoideSubdomainData()
}

static def getAptoideSubdomainsList() {
  def subdomainList = ["en", "pt", "br", "fr", "es", "mx", "de", "it", "ru", "sa", "id", "in", "bd", "mr", "pa",
                       "my", "th", "vn", "tr", "cn", "ro", "mm", "pl", "rs", "hu", "gr", "bg", "nl", "ir"]
  return new ArrayList<>(subdomainList)
}

static def aptoideSubdomainDataWithWildCardPrefix() {
  def subdomainData = ""
  List<String> subdomainList = getAptoideSubdomainsList()
  for (subdomain in subdomainList) {
    subdomainData = subdomainData + data("*." + subdomain + ".aptoide.com")
  }
  return subdomainData
}

static def aptoideSubdomainData() {
  def subdomainData = ""
  List<String> subdomainList = getAptoideSubdomainsList()
  for (subdomain in subdomainList) {
    subdomainData = subdomainData + data(subdomain + ".aptoide.com")
  }
  return subdomainData
}

static def aptoideSubdomainData(String pathPattern) {
  def subdomainData = ""
  List<String> subdomainList = getAptoideSubdomainsList()
  for (subdomain in subdomainList) {
    subdomainData = subdomainData + data(subdomain + ".aptoide.com", pathPattern)
  }
  return subdomainData
}

static def data(String host, String pathPattern) {
  return generateIntentFilter(http(host, pathPattern) + https(host, pathPattern))
}

static def data(String host) {
  return generateIntentFilter(http(host, "") + https(host, ""))
}

static def dataWithPathPrefix(String host, String pathPrefix) {
  return generateIntentFilter(
      createDataTagWithPathPrefix(host, "http", pathPrefix) + createDataTagWithPathPrefix(host,
          "https", pathPrefix))
}

static def http(String host, String pathPattern) {
  if (pathPattern != null && !pathPattern.isEmpty()) {
    createDataTagWithPathPattern(host, "http", pathPattern)
  } else {
    createDataTagWithNoPathPattern(host, "http")
  }
}

static def https(String host, String pathPattern) {
  if (pathPattern != null && !pathPattern.isEmpty()) {
    createDataTagWithPathPattern(host, "https", pathPattern)
  } else {
    createDataTagWithNoPathPattern(host, "https")
  }
}

static def createDataTagWithNoPathPattern(String host, String scheme) {
  return "\n" + "               <data\n" +
      "                   android:host=\"$host\"\n" +
      "                   android:scheme=\"$scheme\"/>\n"
}

static def createDataTagWithPathPattern(String host, String scheme, String pathPattern) {
  return "\n" + "               <data\n" +
      "                   android:host=\"$host\"\n" +
      "                   android:pathPattern=\"$pathPattern\"\n" +
      "                   android:scheme=\"$scheme\"/>\n"
}

static def createDataTagWithPathPrefix(String host, String scheme, String pathPrefix) {
  return "\n" + "               <data\n" +
      "                   android:host=\"$host\"\n" +
      "                   android:pathPrefix=\"$pathPrefix\"\n" +
      "                   android:scheme=\"$scheme\"/>\n"
}

static def generateIntentFilter(String data) {
  return "\n            <intent-filter>\n" +
      "                <action android:name=\"android.intent.action.VIEW\"/>\n" +
      "\n" +
      "                <category android:name=\"android.intent.category.DEFAULT\"/>\n" +
      "                <category android:name=\"android.intent.category.BROWSABLE\"/>\n" +
      "\n" +
      data +
      "            </intent-filter>\n"
}
