try:
    import lasso
except ImportError:
    pass

from wcs.qommon import get_cfg, get_logger
import wcs.qommon.saml2


class Saml2Directory(wcs.qommon.saml2.Saml2Directory):
    def extract_attributes(self, session, login):
        '''Separate attributes as two dictionaries: one for last value, one for
           the list of values.'''
        d = {}
        m = {}

        lasso_session = lasso.Session.newFromDump(session.lasso_session_dump)
        try:
            assertion = lasso_session.getAssertions(None)[0]
        except:
            get_logger().warn('failed to lookup assertion')
            return d, m

        try:
            for attribute in assertion.attributeStatement[0].attribute:
                try:
                    d[attribute.name] = attribute.attributeValue[0].any[0].content
                    for attribute_value in attribute.attributeValue:
                        l = m.setdefault(attribute.name, [])
                        l.append(attribute_value.any[0].content)
                except IndexError:
                    pass
        except IndexError:
            pass
        return d, m

    def fill_user_attributes(self, session, login, user):
        wcs.qommon.saml2.Saml2Directory.fill_user_attributes(self, session, login, user)

        idp = wcs.qommon.saml2.get_remote_provider_cfg(login)
        if not idp.get('attribute-mapping'):
            self.legacy_fill_user_attributes(session, login, user)

    def legacy_fill_user_attributes(self, session, login, user):
        '''Fill fields using a legacy attribute to field varname mapping'''
        d, m = self.extract_attributes(session, login)
        users_cfg = get_cfg('users', {}) or {}
        get_logger().debug('using legacy attribute filling')

        # standard attributes
        user.name = d.get('cn')
        user.email = d.get('mail')

        # email field
        field_email = users_cfg.get('field_email')
        if field_email:
            user.form_data[field_email] = d.get('mail') or d.get('email')

        # name field, this only works if there's a single field for the name
        field_name_values = users_cfg.get('field_name')
        if field_name_values:
            if type(field_name_values) is str: # it was a string in previous versions
                field_name_values = [field_name_values]
            if len(field_name_values) == 1:
                user.form_data[field_name_values[0]] = d.get('cn')

        # other fields, matching is done on known LDAP attribute names and
        # common variable names
        extra_field_mappings = [
                ('gn', ('firstname', 'prenom')),
                ('givenName', ('firstname', 'prenom')),
                ('surname', ('surname', 'name', 'nom',)),
                ('sn', ('surname', 'name', 'nom',)),
                ('personalTitle', ('personalTitle', 'civilite',)),
                ('l', ('location', 'commune', 'ville',)),
                ('streetAddress', ('streetAddress', 'address', 'adresse', 'street',)),
                ('street', ('streetAddress', 'address', 'adresse', 'street',)),
                ('postalCode', ('postalCode', 'codepostal', 'cp',)),
                ('telephoneNumber', ('telephoneNumber', 'telephonefixe', 'telephone',)),
                ('mobile', ('mobile', 'telephonemobile',)),
                ('faxNumber', ('faxNumber', 'fax')),
        ]

        for attribute_key, field_varnames in extra_field_mappings:
            if not attribute_key in d:
                continue
            for field in user.get_formdef().fields:
                if field.varname in field_varnames:
                    user.form_data[field.id] = d.get(attribute_key)
