/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

plugins {
  // Findbugs has been removed as of Gradle 6. Spotbugs is an alternative, if anyone wants to enable it.
//  id 'com.github.spotbugs'
  id 'jacoco'
}

// JaCoCo configuration
def jacocoOff = {
  it.configure {
    jacoco {
      enabled = false
    }
  }
}
def jacocoOn = {
  it.configure {
    jacoco {
      enabled = true
    }
  } 
}

// Default is off
project.tasks.withType(Test).each(jacocoOff)
project.tasks.whenTaskAdded() {
  if (it instanceof Test) {
    it.configure(jacocoOff)
  }
}

if (project.hasProperty("codeCoverage")) {
  // Enable if provided
  project.tasks.withType(Test).each(jacocoOn)
  project.tasks.whenTaskAdded() {
    if (it instanceof Test) {
      it.configure(jacocoOn)
    }
  }

  tasks.register('mergeIntegrationTestCoverage', JacocoMerge) {
    description 'Merges Distributed and Integration test coverage results'

    destinationFile = file("${buildDir}/jacoco/mergedIntegrationTestCoverage.exec")
    executionData = fileTree(dir: 'build/jacoco', include: [
        '**/distributedTest.exec',
        '**/integrationTest.exec'
    ])
  }

  tasks.register('jacocoIntegrationTestReport', JacocoReport) {
    reports {
      csv.enabled false
      sourceSets project.sourceSets.main
      html.outputLocation  = project.file("${buildDir}/reports/jacoco/integrationTest")
      executionData fileTree(dir: 'build/jacoco', include: '**/integrationTest.exec')
    }
  }

  tasks.register('jacocoDistributedTestReport', JacocoReport) {
    reports {
      csv.enabled false
      sourceSets project.sourceSets.main
      html.outputLocation = project.file("${buildDir}/reports/jacoco/distributedTest")
      executionData fileTree(dir: 'build/jacoco', include: '**/distributedTest.exec')
    }
  }

  tasks.register('jacocoOverallTestReport', JacocoReport) {
    reports {
      csv.enabled false
      sourceSets project.sourceSets.main
      html.outputLocation = project.file("${buildDir}/reports/jacoco/all")
      executionData fileTree(dir: 'build/jacoco', include: '**/*.exec')
    }
  }
}
