import groovy.json.JsonSlurper
import io.opentelemetry.api.trace.Span

def sess = request.getAuthSession(true)

def spanCtxt = Span.current().getSpanContext()
def traceparent = "00-${spanCtxt.getTraceId()}-${spanCtxt.getSpanId()}-${spanCtxt.getTraceFlags().asHex()}"
def jsonSlurper = new JsonSlurper()


def lang = (session['ch.nevis.idm.User.language']?:'DE').trim()
def endppoint = "${parameters.get('baseurl')}/api/v1/countries?lang=${lang.toUpperCase()}"
def countryCode = (session['ch.nevis.idm.User.country']?:'CH').trim().toLowerCase()

try {
  LOG.debug("UTILITY: Countries: Request url: ${endppoint}")

  def httpClient = HttpClients.create(parameters)
  def httpResponse = Http.get().url(endppoint).header('traceparent', traceparent).build().send(httpClient)

  LOG.debug('UTILITY: Countries: Response Message: ' + httpResponse.reasonPhrase())
  LOG.debug('UTILITY: Countries: Response Status Code: ' + httpResponse.code())
  LOG.debug('UTILITY: Countries: Response: ' + httpResponse.bodyAsString())

  if (httpResponse.code() == 200) {
    def json = jsonSlurper.parseText(httpResponse.bodyAsString())
    // {"country.af":"Afghanistan","country.al":"Albanie"... }
    def countryName = json["country.${countryCode}"]
    LOG.debug("UTILITY: Countries: countryName for ${countryCode}: ${countryName}")
    if (countryName) {
      sess.setAttribute('agov.countryName', countryName)
    }
  } else {
    LOG.warn("UTILITY: Countries: Failed to fetch country translations. (httpResponse.code: ${httpResponse.code()})")
  }
} catch (Exception e) {
  LOG.warn("UTILITY: Countries: Failed to fetch country translations. (${e})")
}
response.setResult('ok')