""" cart.views """
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext

from catalog.models import Item
from .models import CartItem

from .cart import add_to_cart, get_cart, remove_from_cart, update_cart


def add_item_to_cart(request, sku):
    """Add item to cart """
    item = get_object_or_404(Item, sku=sku)
    add_to_cart(request, item, quantity=1)
    return HttpResponseRedirect(reverse("shopping_cart"))


def remove_item_from_cart(request, cart_token):
    """Add item to cart """
    remove_from_cart(request, cart_token)
    return HttpResponseRedirect(reverse("shopping_cart"))


def __is_quantity_valid(qty):
    """ validate the quantity value"""
    try:
        qty_num = int(qty)
    except ValueError:
        return False
    if qty_num < 0:
        return False
    if qty_num > 1000:
        return False
    return True


def update_item_in_cart(request):
    """ Update item quantity """
    if request.method == "POST":
        postdata = request.POST.copy()
        item_token = postdata.get("item", None)
        qty = postdata.get("quantity", 0)
        item = get_object_or_404(CartItem, cart_token=item_token)
        if not __is_quantity_valid(qty):
            return shopping_cart(request, error_message="Quantity invalid")
        update_cart(request, item, qty)

    return HttpResponseRedirect(reverse("shopping_cart"))


def shopping_cart(request, messages=None, error_message=None):
    """ Show the shopping cart """
    cart = get_cart(request)
    return render_to_response(
        "cart/shopping_cart.html",
        {"cart": cart, "messages": messages, "error_message": error_message},
        context_instance=RequestContext(request),
    )
