import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible
import re



@deconstructible
class UploadPathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path

    def __call__(self, instance, filename):
        file_path = self.path
        ext = filename.split('.')[-1]

        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)
        dynamic_path_strings = re.findall(r"\{([^}]+)\}", file_path)

        for path in dynamic_path_strings:
            field = f"{path.replace('instance.', '')}"
            file_path = file_path.replace(str('{' + path + '}'), str(getattr(instance, field)))

        # return the whole path to the file
        return os.path.join(file_path, filename)