from django import template
from django.template.loader import render_to_string

from ..snippets import safe_json_dumps, parse_product, parse_line

register = template.Library()


def render_datalayer_push(event, data):
    return render_to_string(
        "cookie_jar/gtm/push.html",
        dict(
            event=event,
            data=safe_json_dumps(data),
        ),
    )


@register.simple_tag(takes_context=True)
def gtm_event_add_to_cart(context):
    line = context["line"]

    item = parse_product(line.product)
    item["quantity"] = context["quantity"]

    data = {
        "currency": line.price_currency,
        "value": float(line.price_incl_tax),
        "items": [item],
    }

    return render_datalayer_push("add_to_cart", data)


@register.simple_tag(takes_context=True)
def gtm_event_begin_checkout(context):
    basket = context["basket"]

    data = {
        "currency": basket.currency,
        "value": float(basket.total_incl_tax),
        "items": [parse_line(line) for line in basket.all_lines()],
    }

    return render_datalayer_push("begin_checkout", data)


@register.simple_tag(takes_context=True)
def gtm_event_view_item(context):
    product = context["product"]
    item = parse_product(product)

    if stockrecord := product.stockrecords.first():
        currency = stockrecord.price_currency
    else:
        currency = None

    data = {
        "currency": currency,
        "value": item["price"],
        "items": [item],
    }

    return render_datalayer_push("view_item", data)


@register.simple_tag(takes_context=True)
def gtm_event_view_item_list(context):
    products = context["products"]

    data = {
        "item_list_id": "browse",
        "item_list_name": "Browse",
        "items": [parse_product(product) for product in products],
    }

    return render_datalayer_push("view_item_list", data)
