import groovy.xml.XmlSlurper

def idmSeverityRoleMap = [
    "EnterpriseRoleAdmin": [11, "op-idmlogin.role.accs-mgmt-idm"],
    "ClientRoot": [12, "op-idmlogin.role.support-priv"], 
    "AppAdmin": [20, "op-idmlogin.role.idmcfg-mgmt"],
    "AppOwner": [5, "op-idmlogin.role.accs-mgmt-nonidm"],
    "UserAndUnitAdmin": [7, "op-idmlogin.role.usr-unit-mgmt"],
    "UserAdmin": [6, "op-idmlogin.role.usr-mgmt"],
    "TemplateAdmin": [10, "op-idmlogin.role.support-basic"],
    "Helpdesk": [1, "op-idmlogin.role.readonly-access" ]
]

try {
  def dtoString = session['ch.adnovum.nevisidm.userDto']

  def idmDto = new XmlSlurper().parseText(dtoString)
  def idmPrfMap = idmDto.'**'.findAll 
    { prf -> prf.name() == 'profiles' 
      && prf.'**'.find 
        { role -> role.name() == 'roles' 
          && role.applicationName.text() == 'nevisIdm'
        }
    }.collectEntries { prf -> [ prf.extId.text(), 
            prf.'**'.findAll 
            { role -> role.name() == 'roles' 
              && role.applicationName.text() == 'nevisIdm'
            }.collect{ rolePrioEntry -> idmSeverityRoleMap[rolePrioEntry.name.text()] ?: [1000, "DO-NOT-USE(${rolePrioEntry.name.text()})"] 
            }.sort { a, b -> a[0] <=> b[0] // sort by severity
            }.last()[1] // take label of the ighest one
    ] }

  if ((inargs.getProperty('submit', '') == 'go') && idmPrfMap.containsKey(inargs.getProperty('profile_selection', 'missing'))) {

    // user selected a profile which exists, we take it
    def operationsProfileExtId = inargs.getProperty('profile_selection', 'missing')
    LOG.info("User selected profile: ${operationsProfileExtId} '${idmPrfMap.get(operationsProfileExtId)}'")
    response.setSessionAttribute('operationsProfileExtId', '' + operationsProfileExtId)
    response.setResult('ok')
    return

  } else if (idmPrfMap.size() == 1) {

    // we take the only profile, with an IDM role
    def operationsProfileExtId = idmPrfMap.keySet().first()
    LOG.info("taking the only profile with an idm role: ${operationsProfileExtId} '${idmPrfMap.get(operationsProfileExtId)}'")
    response.setSessionAttribute('operationsProfileExtId', '' + operationsProfileExtId)
    response.setResult('ok')
    return

  } else if (idmPrfMap.isEmpty()) {

    // no profile with an IDM role, do nothing
    response.setResult('ok')
    return

  } else {

    // user should select a profile
    response.setGuiName('op_idmlogin_select_profile')
    idmPrfMap.each {
      response.addRadioGuiField('profile_selection', it.value, it.key)
    }
    response.addButtonGuiField('submit', 'general.continue', 'go')

    response.setStatus(ch.nevis.esauth.auth.engine.AuthResponse.AUTH_CONTINUE)
    return
  }
} catch (Exception e) {
  def errorMsg = "Failed to process profile selection: ${e.getMessage()}"
  LOG.error(errorMsg, e)
  response.setError(9901, errorMsg)
  response.setResult('error')
}