package ru.yandex.atom.utils.config

import com.typesafe.config._
import java.io.File

/**
 * @author avhaliullin
 */
class EnvironmentAwareIncluder(val environment: String,
                               val fallback: ConfigIncluder = ConfigParseOptions.defaults().getIncluder
                                ) extends ConfigIncluder {

  lazy val kungfuConf = ConfigFactory.parseFile(new File(System.getProperty("application.startup.config.json"))).root()

  def withFallback(fallback: ConfigIncluder) = new EnvironmentAwareIncluder(environment, fallback)

  def include(context: ConfigIncludeContext, what: String) = {
    if (what == "kungfu") {
      kungfuConf
    } else {
      val regex = """^(.*)\.(json|conf|properties)$""".r

      val envConfigName = what match {
        case regex(name, extension) => s"$name.$environment.$extension"
        case name => s"$name.$environment"
      }
      val envConfig = fallback.include(context, envConfigName)

      envConfig.withFallback(fallback.include(context, what))
    }
  }
}
