import ch.nevis.idm.client.IdmRestClient
import ch.nevis.idm.client.IdmRestClientFactory
import groovy.json.JsonSlurper
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.ZoneId
import ch.nevis.esauth.auth.engine.AuthResponse
import groovy.xml.XmlSlurper

IdmRestClient idmRestClient = IdmRestClientFactory.get(parameters)

String baseUrl = parameters.get('baseUrl')
String clientExtId = session.get('ch.adnovum.nevisidm.user.clientExtId')
String userExtId = session.get('ch.adnovum.nevisidm.user.extId')
String endPoint = "$baseUrl/api/core/v1/$clientExtId/users/$userExtId/fido2"
String endPointFidoUAF = "$baseUrl/api/core/v1/$clientExtId/users/$userExtId/generic-credentials"

def userDto = new XmlSlurper().parseText(session['ch.adnovum.nevisidm.userDto'])
def hasRecoveryRole = userDto.'**'.find { node -> node.name() == 'roles' && node.applicationName.text() == 'AGOV-AccountStatus' && node.name.text() == 'recovery' }
if (hasRecoveryRole != null) {
  String result
  try {
     result = idmRestClient.get(endPoint)
     resultFidoUAF = idmRestClient.get(endPointFidoUAF)

  def json = new JsonSlurper().parseText(result)
LOG.info('Result fido2: ' + json)

    def login=false
    json['items'].each {
     if ("active".equals(it.stateName)) {
         response.setSessionAttribute('agov.recovery.securityKey', it.userFriendlyName)
         response.setResult('loginWithFido2')
         login=true
         return
      }

   }
   if (login) {
     return
   }
   def jsonFidoUAF = new JsonSlurper().parseText(resultFidoUAF)
   LOG.info('Result fidoUAF: ' + jsonFidoUAF)
      jsonFidoUAF['items'].each {
        if ("active".equals(it.stateName)) {
          response.setSessionAttribute('agov.recovery.accessapp', it.properties.fidouaf_name)
          response.setResult('loginWithFidoUAF')
          login=true
          return
        }
     }
     if (login) {
       return
     }
  } catch(Exception e) {
    LOG.error(e.toString())
    response.setResult('failed')
   return
  }

}
response.setResult('ok')