from django.shortcuts import render, redirect, get_object_or_404
from store.models import Product
from .models import Cart, CartItem, BillingAddress
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.decorators import login_required
from store.forms import CheckoutForm
from accounts.models import User
from django.contrib import messages
from .models import Order


def _cart_id(request):
    cart = request.session.session_key
    if not cart:
        cart = request.session.create()
    return cart


@login_required(login_url='store:account')
def add_cart(request):
    cart_count = 0
    product_id = int(request.GET['id'])
    product_qty = int(request.GET['qty'])
    product = Product.objects.get(id=product_id)
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id=_cart_id(request)
        )
    cart.save()
    try:
        cart_item = CartItem.objects.get(product=product, cart=cart)

        cart_item.quantity += product_qty
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product=product,
            quantity=product_qty,
            cart=cart,
        )
        cart_item.save()
    try:
        cart = Cart.objects.filter(cart_id=_cart_id(request))
        cart_items = CartItem.objects.all().filter(cart=cart[:1])
        for cart_item in cart_items:
            cart_count += cart_item.quantity

    except Cart.DoesNotExist:
        cart_count = 0
    return JsonResponse({'cart_count': cart_count})


@login_required(login_url='store:account')
def add_cart_index(request):
    cart_count = 0
    product_id = int(request.POST['id'])
    product = Product.objects.get(id=product_id)
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id=_cart_id(request)
        )
    cart.save()
    try:
        cart_item = CartItem.objects.get(product=product, cart=cart)

        cart_item.quantity += 1
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product=product,
            quantity=1,
            cart=cart,
        )
        cart_item.save()
    try:
        cart = Cart.objects.filter(cart_id=_cart_id(request))
        cart_items = CartItem.objects.all().filter(cart=cart[:1])
        for cart_item in cart_items:
            cart_count += cart_item.quantity

    except Cart.DoesNotExist:
        cart_count = 0
    return JsonResponse({'cart_count': cart_count})


def remove_cart_item(request):
    cart_id = int(request.POST['id'])
    product_id = int(request.POST['product_id'])
    cart = Cart.objects.get(cart_id=_cart_id(request))
    product = get_object_or_404(Product, id=product_id)
    cart_item = CartItem.objects.get(product=product, cart=cart)
    cart_item.delete()
    data = {'id': product_id}
    return JsonResponse(data)


def incriment_cart(request, total=0, subtotal=0):
    cart_count = 0
    cart_id = int(request.POST['cartid'])
    product_id = int(request.POST['prod_id'])
    cart = Cart.objects.get(cart_id=_cart_id(request))
    product = get_object_or_404(Product, id=product_id)
    cart_item = CartItem.objects.get(product=product, cart=cart)
    cart_items = CartItem.objects.filter(
        cart=cart, is_active=True).order_by('id')
    if cart_item.quantity >= 1:
        cart_item.quantity += 1
        cart_item.save()
        for i in cart_items:
            subtotal += (i.product.product_price * i.quantity)
        total += (cart_item.product.product_price * cart_item.quantity)
    try:
        cart = Cart.objects.filter(cart_id=_cart_id(request))
        cart_items = CartItem.objects.all().filter(cart=cart[:1])
        for cart_item in cart_items:
            cart_count += cart_item.quantity

    except Cart.DoesNotExist:
        cart_count = 0
    data = {
        'subtotal': subtotal,
        'total': total,
        'id': cart_id,
        'cart_count': cart_count
    }
    return JsonResponse(data)


def update_cart(request, total=0, subtotal=0):
    cart_count = 0
    cart_id = int(request.POST['cartid'])
    product_id = int(request.POST['prod_id'])
    product = get_object_or_404(Product, id=product_id)
    cart = Cart.objects.get(cart_id=_cart_id(request))
    cart_item = CartItem.objects.get(cart=cart, product=product)
    if cart_item.quantity > 1:
        cart_items = CartItem.objects.filter(
            cart=cart, is_active=True).order_by('id')
        cart_item.quantity -= 1
        cart_item.save()
        for i in cart_items:
            subtotal += (i.product.product_price * i.quantity)
        total += (cart_item.product.product_price * cart_item.quantity)
        try:
            cart = Cart.objects.filter(cart_id=_cart_id(request))
            cart_items = CartItem.objects.all().filter(cart=cart[:1])
            for cart_item in cart_items:
                cart_count += cart_item.quantity
        except Cart.DoesNotExist:
            cart_count = 0
        data = {
            'quantity': cart_item.quantity,
            'total': total,
            'id': cart_id,
            'subtotal': subtotal,
            'cart_count': cart_count
        }
        return JsonResponse(data)
    else:
        data = {'data': True}
        cart_item.delete()
    return JsonResponse(data)


@login_required(login_url='store:account')
def cart(request, total=0, quantity=0, cart_items=None):
    try:
        cart = Cart.objects.get(cart_id=_cart_id(request))
        cart_items = CartItem.objects.filter(
            cart=cart, is_active=True).order_by('id')
        for cart_item in cart_items:
            total += (cart_item.product.product_price * cart_item.quantity)
            quantity += cart_item.quantity
            context = {
                'total': total,
                'quantity': quantity,
                'cart_items': cart_items,
            }
            return render(request, 'cart.html', context)
    except Cart.DoesNotExist:
        pass
    return render(request, 'cart.html',)


def is_valid_form(values):
    valid = True
    for field in values:
        if field == "":
            valid = False
    return valid


@login_required(login_url='store:account')
def checkout(request, total=0, quantity=0, cart_items=None):
    form = CheckoutForm()
    try:
        cart = Cart.objects.filter(cart_id=_cart_id(request)).first()
        cart_items = CartItem.objects.filter(cart=cart, is_active=True)
        for cart_item in cart_items:
            total += (cart_item.product.product_price * cart_item.quantity)
            quantity += cart_item.quantity
    except CartItem.product.DoesNotExist:
        return redirect('/')
    if request.method == 'POST':
        form = CheckoutForm(request.POST or None)
        if form.is_valid():
            use_default = form.cleaned_data.get('use_default_address')
            if use_default:
                address_qs = BillingAddress.objects.filter(
                    user=request.user,
                    default=True
                )
                ad_id = address_qs.values_list('pk', flat=True)
                addresss_id = list(ad_id)
                request.session['address'] = addresss_id[0]
                return redirect('store:payment')
            else:
                street_address = form.cleaned_data.get('street_address')
                apartment_address = form.cleaned_data.get('apartment_address')
                town_city = form.cleaned_data.get('town_city')
                zip_code = form.cleaned_data.get('zip_code')
                if is_valid_form([street_address, apartment_address, town_city, zip_code]):
                    create_address = BillingAddress(
                        user=request.user,
                        street_address=street_address,
                        town_city=town_city,
                        zip_code=zip_code
                    )
                    create_address.save()
                    request.session['address'] = create_address.id
                    set_default_address = form.cleaned_data.get(
                        'set_default_address')

                    if set_default_address:
                        create_address.default = True
                        create_address.save()
                        request.session['address'] = create_address.id
                    return redirect('store:payment')
                else:
                    messages.info(
                        request, 'Please Fill Up the Form To Continue!')
                    return redirect('basket:checkout')
    request.session['grandtotal'] = total
    context = {
        'total': total,
        'quantity': quantity,
        'cart_items': cart_items,
        'form': form,
    }
    default_address_qs = BillingAddress.objects.filter(
        user=request.user, default=True)

    if default_address_qs.exists():
        context.update({'default_address': default_address_qs[0]})
    return render(request, 'checkout.html', context)


def delete_address(request):
    address_id = int(request.GET['address_id'])
    address = BillingAddress.objects.get(id=address_id)
    address.delete()
    return JsonResponse({'id': address_id})


def edit_address(request):
    address_id = int(request.GET['address_id'])
    address_get = BillingAddress.objects.get(id=address_id)
    address_form = BillingAddressForm(instance=address_get)
    return render(request, 'edit_address_modal.html', {'form': address_form})
