from django.shortcuts import get_object_or_404

from .models import *

def order_product(product, timeframe, formdata):
    """
    Order a product with given parameters
    """

    print(formdata)
    po = ProductOrder(product=product, timeframe=timeframe)
    po.save()

    for res, value in formdata.items():
        print(f"{res}={value}")

        # skip fixed fields
        if res == 'product' or res == 'timeframe':
            continue

        resource = get_object_or_404(Resource, slug=res)
        ro = ResourceOrder.objects.create(value=value, resource=resource)
        po.resources.add(ro)

    # Ordering without a timeframe
    # if not timeframe:
    # product = models.ForeignKey(Product, on_delete=models.CASCADE)
    # timeframe = models.ForeignKey(TimeFrame, null=True, on_delete=models.CASCADE)
    # resources = models.ManyToManyField(ResourceOrder)
