import re

from django.shortcuts import render, get_object_or_404
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.clickjacking import xframe_options_exempt

from products.models import Product, ProductImage, ProductImageFormat


@xframe_options_exempt
def search(request):
    return render(request, 'quickinfo/search.html')


def result(request):
    id = clean_id(request.GET['id'])

    context = {
        'id': id,
    }

    try:
        context['prod'] = Product.objects.filter(sap=id).first()
    except ObjectDoesNotExist:
        context['prod'] = None
        
    context['image'] = ProductImage.get_image_url(id, ProductImageFormat.MED_JPG)

    return render(request, 'quickinfo/result.html', context)


def clean_id(text):
    if not text: return None

    words = list(filter(None, re.compile(r'[^\d]').split(text)))
    if len(words):
        return words[0]
    else:
        return None
