# Path: labshare/models.py
# class EmailAddress(models.Model):
#     user = models.ForeignKey(User, related_name="email_addresses", on_delete=models.CASCADE)
#     email = models.EmailField(max_length=255)
# 
#     def __str__(self):
#         return "{}: {}".format(self.user, self.email)


from django.conf import settings
from django.contrib.auth.models import Group
from django_auth_ldap.backend import LDAPBackend as DjangoLDAPBackend
from labshare.models import EmailAddress



class LDAPBackend(DjangoLDAPBackend):

    def update_mail_addresses(self, user):
        all_saved_email_addresses = [user.email] + [address.email for address in user.email_addresses.all()]
        all_ldap_email_addresses = user.ldap_user.attrs.get(user.ldap_user.settings.USER_ATTR_MAP['email'], [])

        all_saved_email_addresses.sort()
        all_ldap_email_addresses.sort()
        if all_saved_email_addresses != all_ldap_email_addresses:
            # something changed and we need to change all addresses
            user.email = all_ldap_email_addresses[0]
            user.save()

            # first: delete all current addresses and then start over
            EmailAddress.objects.filter(user=user).delete()

            # second: create extra email address objects for user
            for address in all_ldap_email_addresses[1:]:

# Path: labshare/models.py
# class EmailAddress(models.Model):
#     user = models.ForeignKey(User, related_name="email_addresses", on_delete=models.CASCADE)
#     email = models.EmailField(max_length=255)
# 
#     def __str__(self):
#         return "{}: {}".format(self.user, self.email)


# Path: labshare/backends/authentication/ldap.py
from django.conf import settings
from django.contrib.auth.models import Group
from django_auth_ldap.backend import LDAPBackend as DjangoLDAPBackend
from labshare.models import EmailAddress




class LDAPBackend(DjangoLDAPBackend):

    def update_mail_addresses(self, user):
        all_saved_email_addresses = [user.email] + [address.email for address in user.email_addresses.all()]
        all_ldap_email_addresses = user.ldap_user.attrs.get(user.ldap_user.settings.USER_ATTR_MAP['email'], [])

        all_saved_email_addresses.sort()
        all_ldap_email_addresses.sort()
        if all_saved_email_addresses != all_ldap_email_addresses:
            # something changed and we need to change all addresses
            user.email = all_ldap_email_addresses[0]
            user.save()

            # first: delete all current addresses and then start over
            EmailAddress.objects.filter(user=user).delete()

            # second: create extra email address objects for user
            for address in all_ldap_email_addresses[1:]:

                email = EmailAddress.objects.create(user=user, email=address)