""" Checkout views """
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.sites.models import RequestSite

from store_order.models import Order
from cart import cart
from .checkout import create_order
from billing import get_integration

gc = get_integration("google_checkout")
# fps = get_integration("fps")


def checkout(request, template_name="checkout/confirm.html"):
    """ page displayed with order information before order is placed. """
    shopping_cart = cart.get_cart(request)
    if cart.is_empty(request):
        return HttpResponseRedirect(reverse("shopping_cart"))

    order = create_order(request)
    items = []
    for item in shopping_cart.cart_items:
        item_dict = {
            "amount": item.unit_price,
            "name": item.name,
            "description": item.description,
            "currency": "USD",
            "id": item.sku,
            "quantity": item.quantity,
        }
        if item.product.tax_free:
            item_dict["tax-table-selector"] = "TAX_EXEMPT"
        items.append(item_dict)

    shipping_costs = [
        {
            "shipping_type": "flat-rate-shipping",
            "name": "USPS",
            "currency": "USD",
            "price": shopping_cart.cart_shipping_total,
        }
    ]

    gc_taxes = {
        "default-tax-table": {
            "tax-rules": [
                {
                    "shipping-taxed": False,
                    "rate": 0.055,
                    "tax-area": {"us-state-area": ["ME"]},
                }
            ]
        },
        "alternate-tax-tables": [{"name": "TAX_EXEMPT", "standalone": True}],
    }

    private_data = order.pk

    url_scheme = "http"
    if request.is_secure():
        url_scheme = "https"

    gc_return_url = "%s://%s%s" % (
        url_scheme,
        RequestSite(request).domain,
        reverse("checkout_receipt"),
    )

    gc.add_fields(
        {
            "items": items,
            "return_url": gc_return_url,
            "shipping-methods": shipping_costs,
            "private_data": private_data,
            "tax-tables": gc_taxes,
        }
    )

    # caller_reference = shopping_cart.cart_id
    # print("callerReference = {0}".format(caller_reference))
    # fields = {
    #       "itemTotal": shopping_cart.cart_subtotal,
    #       "transactionAmount": shopping_cart.cart_total,
    #       "pipelineName": "SingleUse",
    #       "shipping": shopping_cart.cart_shipping_total,
    #       "callerReference": caller_reference,
    #       'collectShippingAddress': True,
    #       "paymentReason": shopping_cart.purchase_description,
    #       "paymentPage": request.build_absolute_uri(),
    #       "returnURL": "%s://%s%s" % (url_scheme,
    #                                   RequestSite(request).domain,
    #                                   reverse("fps_return_url"))
    #       }
    # print("Fields = {0}".format(fields))
    # Save the fps.fields["callerReference"] in the db along with
    # the amount to be charged or use the user's unique id as
    # the callerReference so that the amount to be charged is known
    # Or save the callerReference in the session and send the user
    # to FPS and then use the session value when the user is back.
    # fps.add_fields(fields)
    context = {
        "gc": gc,
        "shopping_cart": shopping_cart,
        #'fps': fps,
        "order": order,
    }
    # print("View session_key = {0}".format(request.session.session_key))
    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
    )


def receipt(request, template_name="checkout/receipt.html"):
    """ page displayed with order information after an order
    has been placed successfully """
    shopping_cart = cart.get_cart(request)
    try:
        order = Order.objects.get(cart_id=shopping_cart.cart_id)
    except Order.DoesNotExist:
        return HttpResponseRedirect(reverse("shopping_cart"))

    context = {
        "shopping_cart": shopping_cart,
        "order": order,
    }
    # flush the session so that we can't get back
    request.session.flush()
    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
    )
