from apps.product.models import Product
from common.generics import base64_to_image_file
from common.liara_tools import upload_to_liara


class UploadProductImage:
    """
    upload product image
    """

    def upload_image(self, request, product_id):
        product = Product.objects.get(id=product_id)

        image = base64_to_image_file(
            request.data['image'],
            filename=f'product_image_{product}'
        )
        file, file_format = image[0], image[1]

        # upload document to liara
        image_url = upload_to_liara(
            file,
            f'product_image_{product_id}.{file_format}'
        )
        product.img = image_url
        product.save()

        return product
