from django.contrib.auth.models import User

from . import models


def retrieve(request):
    """ gets the StoreProfile instance for a user from the request """
    user = request.user
    return get_profile(user)


def get_profile(user):
    """ returns the StoreProfile for the user creates one if it does not exist
    """
    if not user:
        return None
    if not isinstance(user, User):
        return None

    try:
        profile = user.get_profile()
    except models.StoreProfile.DoesNotExist:
        profile = models.StoreProfile(user=user)
        profile.save()

    return profile


def get_profile_secondary_address(user):
    profile = get_profile(user)
    address, created = models.SecondaryProfileAddress.objects.get_or_create(
        profile=profile
    )
    return address
