from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.dispatch import receiver

from allauth.account.signals import email_confirmed
from allauth.account.models import EmailAddress
import logging

from .signals import post_registration
from .models import Registration


# Define logger for this file
logger = logging.getLogger(__name__)


@receiver(email_confirmed)
def linkUserToMostRecentCustomer(sender,**kwargs):
    '''
    If a new primary email address has just been confirmed, check if the user
    associated with that email has an associated customer object yet.  If not,
    then look for the customer with that email address who most recently
    registered for something and that is not associated with another user.
    Automatically associate the User with with Customer, and if missing, fill in
    the user's name information with the Customer's name.  This way, when a new
    or existing customer creates a user account, they are seamlessly linked to
    their most recent existing registration at the time they verify their email
    address.
    '''
    email_address = kwargs.get('email_address',None)

    if not email_address or not email_address.primary or not email_address.verified:
        return

    user = email_address.user

    if not hasattr(user, 'customer'):
        last_reg = Registration.objects.filter(
            customer__email=email_address.email,
            customer__user__isnull=True,
            dateTime__isnull=False
        ).order_by('-dateTime').first()

        if last_reg:
            customer = last_reg.customer
            customer.user = user
            customer.save()

            if not user.first_name and not user.last_name:
                user.first_name = customer.first_name
                user.last_name = customer.last_name
                user.save()


@receiver(post_registration)
def linkCustomerToVerifiedUser(sender, **kwargs):
    """
    If a Registration is processed in which the associated Customer does not yet
    have a User, then check to see if the Customer's email address has been
    verified as belonging to a specific User, and if that User has an associated
    Customer.  If such a User is found, then associated this Customer with that
    User.  This way, if a new User verifies their email account before they have
    submitted any Registrations, their Customer account is seamlessly linked when
    they do complete their first Registration.
    """
    registration = kwargs.get('registration', None)

    if not registration or (hasattr(registration.customer,'user') and registration.customer.user):
        return

    logger.debug('Checking for User for Customer with no associated registration.')

    customer = registration.customer

    try:
        verified_email = EmailAddress.objects.get(
            email=customer.email,
            verified=True,
            primary=True,
            user__customer__isnull=True
        )

        logger.info("Found user {} to associate with customer {}.".format(verified_email.user.id, customer.id))

        customer.user = verified_email.user
        customer.save()

        if not customer.user.first_name and not customer.user.last_name:
            customer.user.first_name = customer.first_name
            customer.user.last_name = customer.last_name
            customer.user.save()
    except ObjectDoesNotExist:
        logger.info("No user found to associate with customer {}.".format(customer.id))
    except MultipleObjectsReturned as e:
        # This should never happen, as email should be unique in the db table account_emailaddress.
        # If it does, something's broken in the database or Django.
        logger.error(
            "Something's not right with the database: more than one entry found on the database for the email {}. "
            "This duplicate key value violates unique constraint \"account_emailaddress_email_key\". "
            "The email field should be unique for each account.".format(customer.email))
        logger.error("Exception:")
        logger.error(e)

@@ -3002,18 +3002,18 @@
 nd user 
-%7B%7D
+%25s
  to asso
@@ -3032,28 +3032,22 @@
 ustomer 
-%7B%7D.%22.format(
+%25s.%22, 
 verified
@@ -3074,17 +3074,16 @@
 omer.id)
-)
 %0A%0A      
@@ -3464,20 +3464,14 @@
 mer 
-%7B%7D.%22.format(
+%25s.%22, 
 cust
@@ -3478,17 +3478,16 @@
 omer.id)
-)
 %0A    exc
@@ -3513,21 +3513,16 @@
 Returned
- as e
 :%0A      
@@ -3695,33 +3695,16 @@
     
-logger.error(%0A           
+errmsg =
  %22So
@@ -3802,13 +3802,13 @@
 ail 
-%7B%7D. %22
+%25s. %5C
 %0A   
@@ -3816,17 +3816,17 @@
         
-%22
+ 
 This dup
@@ -3905,17 +3905,17 @@
 _key%5C%22. 
-%22
+%5C
 %0A       
@@ -3919,17 +3919,17 @@
         
-%22
+ 
 The emai
@@ -3974,33 +3974,11 @@
 unt.
-%22.format(customer.email))
+%5Cn%22
 %0A   
@@ -3994,23 +3994,16 @@
 er.e
-rror(%22E
 xception
 :%22)%0A
@@ -4002,32 +4002,29 @@
 tion
-:%22)%0A        logger.error(e
+(errmsg, customer.email
 )%0A

Implement code review comments by @merwok