/*
 * 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.
 */

// Debugging/ validation utilities and helpers to aid transition
// to java modules.

allprojects {
  plugins.withType(JavaPlugin) {
    // Show all non-empty package names
    tasks.register("showPackageNames", { task ->
      doFirst {
        listPackageNames(sourceSets).each { println(it) }
      }
    })

    tasks.register("showServiceProviders", { task ->
      doFirst {
        def services = listServices(sourceSets)
        services.each { entry -> {
          println(entry.key)
          entry.value.each { println("  ${it}") }
        }}
      }
    })
  }
}

/* Utility method to collect all package names in a source sets. */
static def listPackageNames(SourceSetContainer sourceSets) {
  var pkgNameSet = [] as Set<String>
  sourceSets.main.each { sourceSet ->
    var dirs = sourceSet.allJava.srcDirTrees.collect { it.dir.toPath() }
    var pattern = new PatternSet()
        .include('**/*.java')
        .exclude('module-info.java')
        .exclude('**/package-info.java')
    sourceSet.allJava.matching(pattern).each {srcFile ->
      var srcPath = srcFile.toPath()
      var dir = dirs.find { srcPath.startsWith(it) }
      var pkgName = srcPath.subpath(dir.nameCount, srcPath.nameCount).parent.stream().map(Object::toString).collect(Collectors.joining('.'))
      pkgNameSet.add(pkgName)
    }
  }
  var pkgNames = pkgNameSet as List<String>
  pkgNames.sort()
  return pkgNames
}

/* Utility method to collect all service providers in a source sets. */
static def listServices(SourceSetContainer sourceSets) {
  def services = [:] as Map<String, List<String>>
  sourceSets.main.each {sourceSet ->
    var pattern = new PatternSet().include('META-INF/services/*')
    sourceSet.resources.matching(pattern).each {file ->
      def serviceName = file.name
      def providers = []
      file.withReader { reader -> {
        reader.lines().each { l ->
          def line = l.trim()
          if (line != "" && !line.startsWith("#")) {
            def provider = line.replace('$', '.')
            providers.add(provider)
          }
        }
      }}
      services.put(serviceName, providers)
    }
  }
  return services
}