""" Checkout utils functions """
from store_order.models import Order, OrderItem, OrderItemGiftDetail
from cart.cart import get_cart_items


def create_order(request):
    """create a new order containing each CartItem instance. If Order
        already exists for this cart, delete and create a new one. That
        means they made a change.
    """
    order = Order.objects.get_order_by_cart(request)
    if order.has_items:
        # if this order has items it means it was from a
        # previous checkout attempt so delete those.
        order.delete_items()

    order.ip_address = request.META.get("REMOTE_ADDR")
    order.user = None
    if request.user.is_authenticated():
        order.user = request.user
    order.status = Order.INIT
    order.save()

    if order.pk:
        # if the order save succeeded
        cart_items = get_cart_items(request)
        for ci in cart_items:
            """ create order item for each cart item """
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.price = ci.unit_price
            oi.product = ci.product
            oi.account_number = ci.account_number
            oi.save()

            if ci.is_gift:
                cigd = ci.gift_detail

                oigd = OrderItemGiftDetail()
                oigd.first_name = cigd.first_name
                oigd.last_name = cigd.last_name
                oigd.company = cigd.company
                oigd.address1 = cigd.address1
                oigd.address2 = cigd.address2
                oigd.city = cigd.city
                oigd.region = cigd.region
                oigd.phone = cigd.phone
                oigd.country = cigd.country
                oigd.postal_code = cigd.postal_code
                oigd.plus_four = cigd.plus_four
                oigd.email = cigd.email
                oigd.bill_on_renewal = cigd.bill_on_renewal
                oigd.gift_card_delivery = cigd.gift_card_delivery
                oigd.message = cigd.message
                oigd.save()

                oi.gift_detail = oigd
                oi.save()

        # all set, clear the cart
        # cart.empty_cart(request)
        # TODO: do this later after we know payment was good.

    return order
