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

def url = parameters.get('url')
def realIpHttpHeaderName = parameters.get('realIpHttpHeaderName') ?: 'X-Real-IP'
def ip = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'

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

  def jsonSlurper = new JsonSlurper()
  def httpClient = HttpClients.create(parameters)
  def httpResponse = Http.get().url(url).header('traceparent', traceparent)
                         .header(realIpHttpHeaderName, ip).build().send(httpClient)

  LOG.debug('Response Status Code: ' + httpResponse.code())
  LOG.debug('Response: ' + httpResponse.bodyAsString())

  if (httpResponse.code() == 200) {
    def json = jsonSlurper.parseText(httpResponse.bodyAsString())

    response.setSessionAttribute('agov.fido2.captchaSettings.enabled', String.valueOf(json.friendlyCaptureClientSettings.enabled))
    response.setSessionAttribute('agov.fido2.captchaSettings.siteKey', json.friendlyCaptureClientSettings.siteKey)
    response.setSessionAttribute('agov.fido2.captchaSettings.puzzleUrl', json.friendlyCaptureClientSettings.puzzleUrl)

    response.setResult('ok')
  } else {
    LOG.error('Unexcpected HTTP response code: ' + httpResponse.code())
    response.setResult('error')
    response.setError(1, 'Unexpected HTTP reponse')
  }
} catch (all) {
  // Handle exception and set the transition
  LOG.error('error: ' + all, all)
  response.setResult('error')
  response.setError(1, 'Exception during HTTP call')
}