import logging
import urllib

from decimal import Decimal

from django import template
from django.conf import settings

register = template.Library()
log = logging.getLogger('store.linkshare_tracking')

DEFAULT_MERCHANT_ID = "123"
PREPARE_LINKSHARE_VALUES = lambda arr: "|".join([str(vl) for vl, item in arr])


@register.simple_tag
def linkshare_pixeltracker(request, order):
    """Method to generate linkshare pixel tracking code
    Usage:
    {% load linkshare_tracking %}

    
    {% linkshare_pixeltracker request order %}
    
    """
    linkshare_host = 'track.linksynergy.com/ep'
    merchant_id = getattr(settings, \
            'LINKSHARE_MERCHANT_ID', DEFAULT_MERCHANT_ID)

    def get_sku_list(order):
        """Get list of SKU of products in order"""
        products_sku = []
        for item in order.orderitem_set.all():
            products_sku.append((item.product.sku, item))
            if item.discount:
                products_sku.append(('Discount', item))
        return products_sku

    def get_qtt_list(order):
        """Get list of quantities of products in order"""
        products_qtt = []
        for sku, item in get_sku_list(order):
            if sku.lower() == 'discount':
                continue
            products_qtt.append((item.quantity.to_integral(), item))
            if item.discount:
                products_qtt.append(('0', item))
        return products_qtt

    def get_amt_list(order):
        """Get list of amounts of all items in order.
        Note that all prices should be without discounts"""
        products_amt = []
        for sku, item in get_sku_list(order):
            if sku.lower() == 'discount':
                continue

            total = Decimal('100') * \
                    item.product.unit_price * item.quantity

            products_amt.append((total.to_integral(), item))
            if item.discount:
                discount = item.discount * Decimal('100')
                products_amt.append(\
                    ("-%s" % str(discount.to_integral()), item))

        return products_amt

    def get_names_list(order):
        """Get list of names of products in order
        """
        products_nm = []
        for sku, item in get_sku_list(order):
            if sku.lower() == 'discount':
                continue

            products_nm.append((item.product.name, item))
            if item.discount:
                products_nm.append(('Discount', item))

        return products_nm

    ls_args = {
    'mid': merchant_id,
    'ord': order.id,
    'skulist': PREPARE_LINKSHARE_VALUES(get_sku_list(order)),
    'qlist': PREPARE_LINKSHARE_VALUES(get_qtt_list(order)),
    'amtlist': PREPARE_LINKSHARE_VALUES(get_amt_list(order)),
    'cur': order.currency_code,
    'namelist': PREPARE_LINKSHARE_VALUES(get_names_list(order)),
    }

    # get http or secured https prefix
    proto = 'http'
    if request.is_secure():
        proto = 'https'

    return '<img src="%(proto)s://%(host)s?%(qs)s" />' % {
    'proto': proto,
    'host': linkshare_host,
    'qs': urllib.urlencode(ls_args),
    }
