import ch.nevis.esauth.auth.engine.AuthResponse
import groovy.xml.XmlSlurper


// AGOVaq conversion
def maxLoiRoleToCtxClssConvertorMap = [
    "level100": "urn:qa.agov.ch:names:tc:ac:classes:100",
    "level200": "urn:qa.agov.ch:names:tc:ac:classes:200",
    "level300": "urn:qa.agov.ch:names:tc:ac:classes:300",
    "level400": "urn:qa.agov.ch:names:tc:ac:classes:400",
    "level500": "urn:qa.agov.ch:names:tc:ac:classes:500"
]

def cleanSession() {
  def s = request.getAuthSession(true)

  s.removeAttribute('agov.op.onboarding.ctxClass')
  s.removeAttribute('agov.op.onboarding.minLoi')
  s.removeAttribute('agov.op.onboarding.homeName')
  s.removeAttribute('agov.op.onboarding.subject')
  s.removeAttribute('agov.op.onboarding.process.state')
  s.removeAttribute('ch.adnovum.nevisidm.userDto')
  s.removeAttribute('saml.response.statusCode')
  if (response.getActualRoles().length > 0) {
    def actualRoles = Arrays.copyOf(response.getActualRoles(), response.getActualRoles().length)
    actualRoles.each{ role -> response.removeActualRole(role) }
  }
}

// for autditing
def user = session['ch.adnovum.nevisidm.user.extId'] ?: 'unknown'
def sourceIp = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'
def userAgent = request.getLoginContext()['connection.HttpHeader.user-agent'] ?: 'unknown'
def maxLoi = 'unknown'


// new
if (session['ch.adnovum.nevisidm.userDto'] != null && notes['lasterror'] == null) {
  try {
    def userDto = new XmlSlurper().parseText(session['ch.adnovum.nevisidm.userDto'])
    def userState = userDto.state
    LOG.debug("Recovery: Dto is '${userDto}")
    LOG.debug("Recovery: state is '${userState}")
    if (userState == 'ACTIVE') {
      def maxLoiList =   userDto.'**'.findAll { node -> node.name() == 'roles' && node.applicationName.text() == 'AGOV-Loi' }.collect({ node -> node.name.text() })
      maxLoi = (maxLoiList == null || maxLoiList.isEmpty()) ? null : maxLoiList.sort().last()
      def accountStatusRoles = userDto.'**'.findAll { node -> node.name() == 'roles' && node.applicationName.text() == 'AGOV-AccountStatus' }.collect({ node -> node.name.text() })
      def hasRecoveryRole = accountStatusRoles.isEmpty() ? null : accountStatusRoles.sort().first()
      LOG.debug("Recovery: MaxLoi is '${maxLoi}'")
      LOG.debug("Recovery: hasRecoveryRole is '${hasRecoveryRole}'")
      if (maxLoi != null && maxLoiRoleToCtxClssConvertorMap.containsKey(maxLoi)) {       
              response.setResult('ok')
              return
      } else {
        LOG.debug("Recovery: no 'AGOV-Loi'-role assigned to user ${user}")
              response.setResult('notFullyRegistered')
              return
      }
    } else {
      // state != ACTIVE and no lasterror should not happen
      LOG.error("Recovery: state='${userState}' but not lasterror set")
      response.setNote('lasterror', '9909')
      response.setNote('lasterrorinfo', 'internal error')
      response.setResult('error')
      return
    }
  } catch (Exception e) {
    LOG.error("Recovery processing failed: Exception " + e)
    response.setNote('lasterror', '9909')
    response.setNote('lasterrorinfo', 'internal error')
      response.setResult('error')
      return
  }
}

              response.setResult('error')
              return

// new