""" Google checkout integration for django-merchant """
import logging

from billing.integrations.google_checkout_integration import (
    GoogleCheckoutIntegration as Integration,
)
from billing.models import GCNewOrderNotification
from billing import signals

from store_order.models import Order, OrderPayment

LOGGER = logging.getLogger("gc_integration")

BUTTON_SANDBOX_URL_SSL = "https://sandbox.google.com/checkout/buttons/checkout.gif?merchant_id=%(merchant_id)s&w=%(width)s&h=%(height)s&style=white&variant=text&loc=en_US"
BUTTON_URL_SSL = "https://checkout.google.com/checkout/buttons/checkout.gif?merchant_id=%(merchant_id)s&w=%(width)s&h=%(height)s&style=white&variant=text&loc=en_US"


class GcIntegration(Integration):

    # remove once this is fixed in django-merchant
    def button_image_url(self):
        params = {
            "merchant_id": self.merchant_id,
            "width": self.button_width,
            "height": self.button_height,
        }
        if self.test_mode:
            return BUTTON_SANDBOX_URL_SSL % params
        return BUTTON_URL_SSL % params

    def gc_order_state_change_notification(self, request):
        """ used when a the GC order changed state """
        LOGGER.debug("[gc_order_state_change_notification] new update")
        post_data = request.POST.copy()
        # TODO, clean this up, only for testing.
        LOGGER.debug(
            "[gc_order_state_change_notification] data = {0}".format(post_data)
        )
        try:
            order = GCNewOrderNotification.objects.get(
                google_order_number=post_data["google-order-number"]
            )
        except GCNewOrderNotification.DoesNotExist:
            LOGGER.info("[gc_order_state_change_notification] object not found!")
            return

        order.financial_order_state = post_data["new-financial-order-state"]

        try:
            order_payments = order.order_payment.all()
            if order_payments:
                order_payment = order_payments[0]
                orig_order = order_payment.order
            else:
                orig_order = None
        except Exception as exp:
            LOGGER.error("[gc_order_state_change_notification] Error = {0}".format(exp))
            orig_order = None

        # Send success signal when order state is charged
        if order.financial_order_state == "CHARGED":
            signals.transaction_was_successful.send(
                sender=self.__class__, type="purchase", response=order
            )
            if orig_order:
                LOGGER.debug(
                    "[gc_order_state_change_notification] status changed to processed"
                )
                orig_order.status = Order.PROCESSED
                orig_order.save()
                # Ideally we'd call this in a signal receiver above, but
                # I wasn't able to get the signal to work.
                from storefront.subscriptions import send_subscription_email

                send_subscription_email(orig_order)

        elif order.financial_order_state in ["CANCELLED", "CANCELLED_BY_GOOGLE"]:
            if orig_order:
                LOGGER.debug(
                    "[gc_order_state_change_notification] status changed to cancelled"
                )
                orig_order.status = Order.CANCELLED
                orig_order.save()

        order.fulfillment_order_state = post_data["new-fulfillment-order-state"]

        if order.fulfillment_order_state == "DELIVERED":
            if orig_order:
                LOGGER.debug(
                    "[gc_order_state_change_notification] status changed to shipped"
                )
                orig_order.status = Order.SHIPPED
                orig_order.save()

        order.save()

    def gc_new_order_notification(self, request):
        """ new GC order coming in"""
        LOGGER.debug("New GC Order")
        post_data = request.POST.copy()
        data = {}
        resp_fields = {
            "_type": "notify_type",
            "serial-number": "serial_number",
            "google-order-number": "google_order_number",
            "buyer-id": "buyer_id",
            "buyer-shipping-address.contact-name": "shipping_contact_name",
            "buyer-shipping-address.address1": "shipping_address1",
            "buyer-shipping-address.address2": "shipping_address2",
            "buyer-shipping-address.city": "shipping_city",
            "buyer-shipping-address.postal-code": "shipping_postal_code",
            "buyer-shipping-address.region": "shipping_region",
            "buyer-shipping-address.country-code": "shipping_country_code",
            "buyer-shipping-address.email": "shipping_email",
            "buyer-shipping-address.company-name": "shipping_company_name",
            "buyer-shipping-address.fax": "shipping_fax",
            "buyer-shipping-address.phone": "shipping_phone",
            "buyer-billing-address.contact-name": "billing_contact_name",
            "buyer-billing-address.address1": "billing_address1",
            "buyer-billing-address.address2": "billing_address2",
            "buyer-billing-address.city": "billing_city",
            "buyer-billing-address.postal-code": "billing_postal_code",
            "buyer-billing-address.region": "billing_region",
            "buyer-billing-address.country-code": "billing_country_code",
            "buyer-billing-address.email": "billing_email",
            "buyer-billing-address.company-name": "billing_company_name",
            "buyer-billing-address.fax": "billing_fax",
            "buyer-billing-address.phone": "billing_phone",
            "buyer-marketing-preferences.email-allowed": "marketing_email_allowed",
            "order-adjustment.total-tax": "total_tax",
            "order-adjustment.total-tax.currency": "total_tax_currency",
            "order-adjustment.adjustment-total": "adjustment_total",
            "order-adjustment.adjustment-total.currency": "adjustment_total_currency",
            "order-total": "order_total",
            "order-total.currency": "order_total_currency",
            "financial-order-state": "financial_order_state",
            "fulfillment-order-state": "fulfillment_order_state",
            "timestamp": "timestamp",
            "shopping-cart.merchant-private-data": "private_data",
        }

        for (key, val) in resp_fields.iteritems():
            data[val] = post_data.get(key, "")

        data["num_cart_items"] = len(post_data.getlist("shopping-cart.items"))
        data["cart_items"] = self.gc_cart_items_blob(post_data)
        resp = GCNewOrderNotification.objects.create(**data)

        try:
            order_id = int(resp.private_data)
            order = Order.objects.get(pk=order_id)
            order_payment = OrderPayment()
            order_payment.order = order
            order_payment.google_payment = resp
            order_payment.save()
            # order.orderpayment = order_payment
            order.status = Order.SUBMITTED
            # TODO: Make sure status is set correctly.
            order.save()
            LOGGER.debug("New GC Order saved!")
        except Exception as exc:
            # TODO log error, send email.
            LOGGER.error("[gc_new_order_notification] Error = {0}".format(exc))
