from allauth.account.models import EmailAddress

from .models import Address, User
from .tasks import send_account_created_email


def get_or_create_customer(request, form, shipping_address):
    address, a_created = Address.objects.get_or_create(
        first_name=shipping_address['first_name'],
        last_name=shipping_address['last_name'],
        street_address_1=shipping_address['street_address_1'],
        street_address_2=shipping_address['street_address_2'],
        city=shipping_address['city'],
        state=shipping_address['state'],
        postal_code=shipping_address['postal_code']
    )

    if request.user.is_authenticated:
        user = request.user
        user.addresses.add(address)
        if not user.default_shipping_address:
            user.default_shipping_address = address
        user.save()
    else:
        user, u_created = User.objects.get_or_create(
            email=form.cleaned_data['email'],
            defaults={
                'username': form.cleaned_data['email'].lower(),
                'is_staff': False,
                'is_active': True,
                'is_superuser': False,
                'first_name': form.cleaned_data['first_name'],
                'last_name': form.cleaned_data['last_name'],
                'default_shipping_address': address,
            }
        )
        if u_created:
            password = User.objects.make_random_password()
            user.set_password(password)
            user.addresses.add(address)
            user.save()

            EmailAddress.objects.create(
                user=user, email=user.email, primary=True, verified=False
            )

            u = {
                'full_name': user.get_full_name(),
                'email': user.email,
                'password': password
            }

            send_account_created_email.delay(u)

    return user, address
