""" Cart model managers """
from django.db import models
from django.core.exceptions import MultipleObjectsReturned
from django.contrib.contenttypes.models import ContentType


class CartManager(models.Manager):
    """ shopping cart manager """

    def for_request(self, request):
        """ get a cart from a request """
        # short circuit if they don't have a session yet.
        if not request.session.session_key:
            # manually set it as modified so it gets created for us
            request.session.modified = True
            return None

        lookup_kwargs = {"cart_id": request.session.session_key}
        try:
            cart, new = self.get_or_create(**lookup_kwargs)
            # associate the logged in user to cart, if they are logged in.
            if new and request.user.is_authenticated():
                cart.owner = request.user
                cart.save()
        except MultipleObjectsReturned:
            cart = self.filter(**lookup_kwargs).order_by("id")[0]
        return cart

    def for_session(self, session_key):
        """ get a cart from a session """
        lookup_kwargs = {
            "cart_id": session_key,
        }
        try:
            cart, new = self.get_or_create(**lookup_kwargs)
        except MultipleObjectsReturned:
            cart = self.filter(**lookup_kwargs).order_by("id")[0]
        return cart


class CartItemManager(models.Manager):
    """ Cart Item manager"""

    def item_for_request(self, session_key, item_token):
        """ get an item from a request """
        return self.get(cart_token=item_token, cart__session_key=session_key)

    def get(self, *args, **kwargs):
        """ get a cart items """
        if "product" in kwargs:
            kwargs["content_type"] = ContentType.objects.get_for_model(
                type(kwargs["product"])
            )
            kwargs["object_id"] = kwargs["product"].pk
            del kwargs["product"]
        return super(CartItemManager, self).get(*args, **kwargs)
