import groovy.json.JsonBuilder
import ch.nevis.esauth.auth.engine.AuthResponse


def getHeader(String name) {
    def inctx = request.getLoginContext()
    // case-insensitive lookup of HTTP headers
    def map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER)
    map.putAll(inctx)
    return map['connection.HttpHeader.' + name]
}

def clearFidoUAFSession() {
    def s = request.getAuthSession(true)
    s.removeAttribute('ch.nevis.auth.fido.uaf.fidouafsessionid')
    inargs.remove('fallback')
}


// dispatch AJAX calls and form POST when operation is done
if (inargs['fidoUafDone'] == 'true' ||
    inargs.containsKey('o.fidoUafSessionId.v') ||
    getHeader('Content-Type') == 'application/json') {

  if (inargs.containsKey('o.fidoUafSessionId.v') && (inargs['o.fidoUafSessionId.v'] != session['ch.nevis.auth.fido.uaf.fidouafsessionid'])) {
      // received polling for wrong fido session; make sure, that stops
      LOG.debug("received polling for wrong fido session ${inargs['o.fidoUafSessionId.v']} (correct: ${session['ch.nevis.auth.fido.uaf.fidouafsessionid']})")
      def json = new JsonBuilder()
      json {
          "status" "unknown"
          "timestamp" org.joda.time.DateTime.now().toString()
      }
      String body = json.toString()

      response.setContent(body)
      response.setContentType('application/json')
      response.setHttpStatusCode(200)
      response.setIsDirectResponse(true)
      response.setStatus(AuthResponse.AUTH_CONTINUE)
      return
  }

  // continue with OutOfBandFidoUafAuthState
  response.setResult('ok')
}


// dispatch form post with onReload input field : refresh QR-code FIDO UAF
if (inargs.containsKey('onReload')) {
    clearFidoUAFSession()
    response.setResult('default')
}

