# Path: grapevine/emails/utils.py
# def parse_email(address):
#     """
#     Returns "Marco Polo", "marco@polo.com" from "Marco Polo <marco@polo.com"
#     Returns "", "marco@polo.com" from "marco@polo.com"
#     """
#     if ' ' in address.strip():
#         assert '<' in address and '>' in address, "Invalid address structure: %s" % (address,)
#         parts = address.split(' ')
#         name = ' '.join(parts[:-1])
#         address = parts[-1][1:-1]
# 
#         return name, address
#     else:
#         return "", address


from django.db import models
from grapevine.emails.utils import parse_email

class EmailManager(models.Manager):

    def create(self, **kwargs):
        """
        Takes and appropriately processes the extra keyword args:
            `recipients` and `{backend|backend_id}`
        """
        recipients = kwargs.pop('to', None)

        key, backend = self.model.determine_backend(**kwargs)
        if backend:
            # If we matched a backend, great
            kwargs[key] = backend

        obj = super(EmailManager, self).create(**kwargs)

        if recipients:
            obj.add_recipients(recipients)

        return obj


class EmailRecipientManager(models.Manager):

    def create(self, **kwargs):
        """
        Handles normal `create` duties, plus some additional "address" parsing
        """
        address = kwargs.get('address', '')

# Path: grapevine/emails/utils.py
# def parse_email(address):
#     """
#     Returns "Marco Polo", "marco@polo.com" from "Marco Polo <marco@polo.com"
#     Returns "", "marco@polo.com" from "marco@polo.com"
#     """
#     if ' ' in address.strip():
#         assert '<' in address and '>' in address, "Invalid address structure: %s" % (address,)
#         parts = address.split(' ')
#         name = ' '.join(parts[:-1])
#         address = parts[-1][1:-1]
# 
#         return name, address
#     else:
#         return "", address


# Path: grapevine/emails/managers.py
from django.db import models
from grapevine.emails.utils import parse_email


class EmailManager(models.Manager):

    def create(self, **kwargs):
        """
        Takes and appropriately processes the extra keyword args:
            `recipients` and `{backend|backend_id}`
        """
        recipients = kwargs.pop('to', None)

        key, backend = self.model.determine_backend(**kwargs)
        if backend:
            # If we matched a backend, great
            kwargs[key] = backend

        obj = super(EmailManager, self).create(**kwargs)

        if recipients:
            obj.add_recipients(recipients)

        return obj


class EmailRecipientManager(models.Manager):

    def create(self, **kwargs):
        """
        Handles normal `create` duties, plus some additional "address" parsing
        """
        address = kwargs.get('address', '')

        name, address = parse_email(address)