from django.shortcuts import render,redirect
from .models import Cart# Create your views here.
from image_data.models import Product

def cart_home(request):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    return render(request, "carts/home.html", {"cart": cart_obj})


def cart_update(request):
    product_id = request.POST.get('product_id')
    
    if product_id is not None:
        try:
            product_obj = Product.objects.get(id=product_id)
            print(product_obj)
        except Product.DoesNotExist:
            print("Show message to user, product is gone?")
            return redirect("home")
        cart_obj, new_obj = Cart.objects.new_or_get(request)
        print(cart_obj.products.all())
        if product_obj in cart_obj.products.all():
            cart_obj.products.add(product_obj)
            added = False
        else:
            cart_obj.products.add(product_obj) # cart_obj.products.add(product_id)
            added = True
 
    return redirect("cart")
