from django.db import models
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from froide.account.models import User


def convert_bounce_info(bounce_info):
    d = dict(bounce_info._asdict())
    d['timestamp'] = d['timestamp'].isoformat()
    return d


class BounceManager(models.Manager):
    def update_bounce(self, email, bounce_info):
        email = email.lower()
        try:
            bounce = Bounce.objects.get(email=email.lower())
            bounce.last_update = timezone.now()
            bounce.bounces.append(
                convert_bounce_info(bounce_info)
            )
            bounce.save()
        except Bounce.DoesNotExist:
            try:
                user = User.objects.get(email__iexact=email)
            except User.DoesNotExist:
                user = None
            bounce = Bounce.objects.create(
                email=email,
                user=user,
                bounces=[convert_bounce_info(bounce_info)]
            )
        return bounce


class Bounce(models.Model):
    email = models.EmailField(max_length=255)

    user = models.ForeignKey(
        User, null=True, blank=True,
        on_delete=models.CASCADE
    )
    bounces = JSONField(default=list, blank=True)
    last_update = models.DateTimeField(default=timezone.now)

    objects = BounceManager()

    class Meta:
        verbose_name = _('Bounce')
        verbose_name_plural = _('Bounces')

    def __str__(self):
        return '{} ({})'.format(self.email, len(self.bounces))

@@ -443,16 +443,22 @@
    email
+_lower
  = email
@@ -530,24 +530,22 @@
 il=email
-.
+_
 lower
-()
 )%0A      
@@ -754,32 +754,36 @@
             
-try:%0A   
+user = None%0A
             
@@ -782,21 +782,21 @@
         
- 
 user
+s
  = User.
@@ -799,27 +799,30 @@
 ser.objects.
-get
+filter
 (email__iexa
@@ -829,16 +829,22 @@
 ct=email
+_lower
 )%0A      
@@ -853,61 +853,238 @@
     
-except User.DoesNotExist:%0A                user = None
+if len(users) %3E 1:%0A                try:%0A                    user = User.objects.get(email=email)%0A                except User.DoesNotExist:%0A                    pass%0A            if users and not user:%0A                user = users%5B0%5D
 %0A   

Handle multiple users with differently cased email