buildscript {
	repositories {
		mavenCentral()
		maven { url "https://jitpack.io" }
		jcenter()
		google()
	}
	dependencies {
		classpath 'com.android.tools.build:gradle:8.3.0'
		classpath 'com.noveogroup.android:check:1.2.5', {
			exclude module: 'checkstyle'
			exclude module: 'xmlpull'
		}
		classpath 'com.puppycrawl.tools:checkstyle:7.8.1'
		classpath 'com.github.bjoernq:unmockplugin:0.7.9'
	}
}
apply plugin: 'com.android.application'
apply plugin: 'com.noveogroup.android.check'
apply plugin: 'de.mobilej.unmock'

// enable verbose lint warnings
gradle.projectsEvaluated {
	tasks.withType(JavaCompile) {
		options.compilerArgs <<
				'-Xlint:deprecation' <<
				'-Xlint:unchecked' <<
				'-Xdiags:verbose'
	}
}

repositories {
	maven { url "${System.env.ANDROID_HOME}/extras/android/m2repository/" }
	mavenCentral()
	maven { url 'https://s3.amazonaws.com/repo.commonsware.com' }
	google()
}

def excludeKxml2 = {
	// This transitive dependency is excluded from some direct dependencies to prevent
	// "Program type already present: org.xmlpull.v1.XmlSerializer" when running
	// `gradle clean transformDexArchiveWithExternalLibsDexMergerForGenericDebugAndroidTest`
	// This class is also included in the android core libs by default, so this should
	// be safe to exclude from androidTestImplementation and implementation configurations.
	exclude module: 'kxml2'
}

dependencies {
	testImplementation 'androidx.test:core:1.4.0'
	testImplementation 'com.google.android:android-test:4.1.1.4'
	testImplementation 'org.robolectric:robolectric:4.7'
	testImplementation 'com.squareup.okhttp3:mockwebserver:3.2.0'
	testImplementation 'org.mockito:mockito-core:4.0.0'
	testImplementation 'junit:junit:4.13.2'

	androidTestImplementation 'com.google.android:android-test:4.1.1.4'
	androidTestImplementation 'com.squareup.okhttp3:mockwebserver:4.9.2'
	androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
	androidTestImplementation 'androidx.test:rules:1.4.0'
	androidTestImplementation 'androidx.test.ext:junit:1.1.3'

	implementation 'androidx.legacy:legacy-support-core-ui:1.0.0'
	implementation 'androidx.fragment:fragment:1.0.0'
	implementation 'com.commonsware.cwac:wakeful:1.1.0'
	implementation 'com.google.code.findbugs:annotations:3.0.1', {
		// Need to exclude these, or build is broken by:
		//   com.android.dex.DexException: Multiple dex files define Ljavax/annotation/CheckForNull
		exclude module: 'jsr305'
		exclude module: 'jcip-annotations'
	}

	coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

def getVersionCode = {
  int versionCode = 1
  if(System.env.CI == 'true' && System.env.GIT_TAG && System.env.GIT_TAG.startsWith('v')) {
    def versionParts = System.env.GIT_TAG.split(/[^0-9]+/)

    if (versionParts.length != 4 && versionParts.length != 5)
      throw new RuntimeException("Unexpected version number - should be of formatted as 'v1.2.3' or 'v1.2.3-alpha.4', but was: $System.env.GIT_TAG")

    versionParts = versionParts.drop(1).collect { Integer.parseInt(it) }
    int alphaPart = versionParts.size() == 4 ? versionParts[3] : 99;

    if (versionParts[1] > 99 || versionParts[2] > 99 || alphaPart > 99)
      throw new RuntimeException('Version part greater than 99 not allowed.')

    versionCode = (100 * 100 * 100 * versionParts[0]) + (100 * 100 * versionParts[1]) + (100 * versionParts[2]) + alphaPart
    if (versionCode > 2100000000 / 10)
      throw new RuntimeException('versionCode bigger than max allowed by Google Play.')
  }

  return versionCode
}

def getVersionName = {
  System.env.GIT_TAG ?: 'SNAPSHOT'
}

android {
	compileSdkVersion 30
	buildToolsVersion '30.0.3'
    packagingOptions {
        resources {
            excludes += ['META-INF/LICENSE', 'META-INF/NOTICE']
        }
    }


    defaultConfig {
		minSdkVersion 16
		targetSdkVersion 29	// 30+ causes instrumentation tests to fail when uninstalling the app from the device

		versionCode getVersionCode()
		versionName getVersionName()
		archivesBaseName = "${project.name}-${versionName}"

		testInstrumentationRunner 'medic.gateway.alert.test.WakingJUnitRunner'

		multiDexEnabled true
	}

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
  }

	applicationVariants.all {
		buildConfigField "String", "LOG_TAG", '"CHTGateway"'
		buildConfigField "boolean", "DISABLE_APP_URL_VALIDATION", "Boolean.parseBoolean(\"${System.env.DISABLE_APP_URL_VALIDATION}\")"

		buildConfigField "boolean", "CI", "Boolean.parseBoolean(\"${System.env.CI}\")"
		buildConfigField "boolean", "FORCE_SEED", "Boolean.parseBoolean(\"${System.env.FORCE_SEED}\")"
		buildConfigField "boolean", "LOAD_SEED_DATA", "Boolean.parseBoolean(\"${System.env.LOAD_SEED_DATA}\")"

		buildConfigField "boolean", "IS_DUMMY_SEND_AVAILABLE", "Boolean.parseBoolean(\"${System.env.ENABLE_DUMMY_SEND_OPTION}\")"
	}

	sourceSets {
		test { java.srcDirs = [ 'src/test/java', 'src/libTest/java' ] }
		androidTest { java.srcDirs = [ 'src/androidTest/java', 'src/libTest/java' ] }
	}

	signingConfigs {
		release {
			storeFile file(System.env.ANDROID_KEYSTORE_PATH ?: signingConfigs.debug.storeFile)
			storePassword System.env.ANDROID_KEYSTORE_PASSWORD ?: signingConfigs.debug.storePassword
			keyAlias System.env.ANDROID_KEY_ALIAS ?: signingConfigs.debug.keyAlias
			keyPassword System.env.ANDROID_KEY_PASSWORD ?: signingConfigs.debug.keyPassword
		}
	}

	buildTypes {
		debug {
			testCoverageEnabled = true
		}
		release {
			minifyEnabled true
			shrinkResources true
			proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'config/proguard.pro'
			signingConfig signingConfigs.release
		}
	}

	check {
		abortOnError true
	}


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

	flavorDimensions 'brand'
	productFlavors {
		generic {
			applicationId = 'medic.gateway.alert.generic'
			buildConfigField "boolean", "IS_GENERIC_FLAVOUR", "true"
			buildConfigField "boolean", "IS_MEDIC_FLAVOUR", "false"
		}
		medic {
			applicationId = 'medic.gateway.alert'
			buildConfigField "boolean", "IS_GENERIC_FLAVOUR", "false"
			buildConfigField "boolean", "IS_MEDIC_FLAVOUR", "true"
		}
	}
    namespace 'medic.gateway.alert'
    lint {
        abortOnError false
        disable 'UnusedResources', 'GradleDependency', 'JcenterRepositoryObsolete', 'RtlHardcoded'
        warningsAsErrors true
        xmlReport false
    }
	buildFeatures {
		buildConfig true
	}
}

unMock {
	keep 'android.net.Uri'
}

//Skip Findbugs
afterEvaluate { project ->
	project.tasks.androidFindbugs {
		onlyIf  {
			println 'Skipping...'
			return false
		}
	}
}