from django.db import models
from uuid import uuid4
from django.utils.deconstruct import deconstructible
import os
from polysite import settings

@deconstructible
class UploadToPathAndRename(object):

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

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(self.sub_path, filename)

class BlogImage(models.Model):
    title = models.CharField(max_length = 100)
    caption = models.CharField(max_length = 300)
    date = models.DateTimeField()
    image = models.ImageField(upload_to = UploadToPathAndRename(""))

    def __str__(self):
        return self.title

