from django import template

from oscar.core.loading import get_class
from oscar.templatetags.history_tags import recently_viewed_products

from ocyan.plugin.oscar_basket.models import BasketPopupProducts

register = template.Library()


@register.simple_tag(takes_context=True)
def get_product_add_alert_content(context, prod_id):
    """
    Returns the product added to basket,
    best sold products in the same category as the one in the product and related products.
    """
    # Avoid circularing import
    ProductElasticsearchIndex = get_class(
        "search.api.product", "ProductElasticsearchIndex"
    )
    # Remove it from session, otherwise we'll always get that popup lol.
    request = context["request"]
    request.session.pop("added_product", None)
    filters = [{"term": {"id": prod_id}}]
    search_product = ProductElasticsearchIndex().search(from_=0, to=5, filters=filters)
    product = search_product[0].get()
    recommand_products = BasketPopupProducts.objects.filter(product__is_public=True)

    return {
        "added_product": product,
        "recently_viewed_products": recently_viewed_products(context)["products"][:6],
        "custom_recommand_products": (
            recommand_products if recommand_products.exists() else False
        ),
    }
