from django.conf import settings
from docbow_project.docbow.models import DocbowProfile


def get_tabellio_id(saml_attributes):
    tabellio_key = getattr(settings, 'TABELLIO_IDENTIFER_KEY', 'tabellio_pers_id')
    if tabellio_key not in saml_attributes:
        return None
    value = saml_attributes[tabellio_key]
    if not isinstance(value, (tuple, list)):
        return value
    if not value:
        return None
    return value[0]


try:

    import mellon.adapters
    import mellon.models

    class PFWBMellonAdapter(mellon.adapters.DefaultAdapter):
        def lookup_by_attributes(self, idp, saml_attributes):
            tabellio_id = get_tabellio_id(saml_attributes)
            if tabellio_id:
                try:
                    profile = DocbowProfile.objects.get(external_id=tabellio_id)
                    return profile.user
                except DocbowProfile.DoesNotExist:
                    pass

            return super(PFWBMellonAdapter, self).lookup_by_attributes(idp, saml_attributes)

        def provision(self, user, idp, saml_attributes):
            super(PFWBMellonAdapter, self).provision(user, idp, saml_attributes)
            tabellio_id = get_tabellio_id(saml_attributes)
            if tabellio_id:
                try:
                    profile = user.docbowprofile
                except DocbowProfile.DoesNotExist:
                    profile = DocbowProfile.objects.create(user=user)
                if profile.external_id != tabellio_id:
                    profile.external_id = tabellio_id
                    profile.save()

except ImportError:
    pass
