/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *      https://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.
 */

// This module contains config loading functions for EN Express.
// This module gathers a collection of configs/.json
// TODO: Link to documentation of config format.

import groovy.json.JsonSlurper


static def getConfigPrefix(file) {
  return file.getName().split("\\.")[0]
}

def loadConfigFiles() {
  def configPath = "$rootDir/app/configs"
  def configFiles = fileTree(configPath).findAll {
    it.getName().endsWith(".json")
  }
  Map configData = [:]
  configFiles.each {
    def jsonSlurper = new JsonSlurper()
    def config = jsonSlurper.parseText(it.text)['config']
    def files = [it]
    def name = getConfigPrefix(it)
    config["name"] = name
    // If there's a .extra file override those fields.
    def extraConfig = new File("$rootDir/app/configs/" + name + ".extra")
    if (extraConfig.exists()) {
      def extraData = jsonSlurper.parseText(extraConfig.text)
      extraData.each { k, v -> config[k] = v }
      files.add(extraConfig)
    }
    config["files"] = files
    configData[name] = config
  }
  return configData
}

ext {
  loadConfigFiles = this.&loadConfigFiles
}
