from django.db import models
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from tagging.utils import parse_tag_input
from django.contrib.auth.models import User
from django.conf import settings
import uuid,os
import datetime
# Create your models here.

def slugify_uniquely(value, model, slugfield="slug"):
        """Returns a slug on a name which is unique within a model's table

        This code suffers a race condition between when a unique
        slug is determined and when the object with that slug is saved.
        It's also not exactly database friendly if there is a high
        likelyhood of common slugs being attempted.

        A good usage pattern for this code would be to add a custom save()
        method to a model with a slug field along the lines of:

                from django.template.defaultfilters import slugify

                def save(self):
                    if not self.id:
                        # replace self.name with your prepopulate_from field
                        self.slug = SlugifyUniquely(self.name, self.__class__)
                super(self.__class__, self).save()

        Original pattern discussed at
        http://www.b-list.org/weblog/2006/11/02/django-tips-auto-populated-fields
        """
        suffix = 0
        potential = base = slugify(value)
        while True:
                if suffix:
                        potential = "-".join([base, str(suffix)])
                if not model.objects.filter(**{slugfield: potential}).count():
                        return potential
                # we hit a conflicting slug, so bump the suffix & try again
                suffix += 1

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (instance.uuid, ext)
    return os.path.join(settings.LOCAL_PHOTO_STORAGE_FOLDER, filename)

class TrovePhoto(models.Model):
    user = models.ForeignKey(User)
    full_size = models.URLField(max_length=255)
    thumbnail = models.URLField(max_length=255)
    trove_id = models.CharField(max_length=200)
    
    def get_absolute_url(self):
        return self.url
    
class LocalPhoto(models.Model):
    user = models.ForeignKey(User)
    uuid = models.CharField(max_length=200)
    title = models.CharField(max_length=100,null=True,blank=True)
    description = models.CharField(max_length=200,null=True,blank=True)
    photo = models.ImageField(upload_to=get_file_path,null=True,blank=True)
    date_uploaded = models.DateTimeField()
    tags = TagField()
    thumbnail = models.ImageField(upload_to="thumbnails/", editable=False)

    def save(self):
        if not self.id:
            self.date_uploaded = datetime.datetime.now()
            
            from PIL import Image
            from cStringIO import StringIO
            from django.core.files.uploadedfile import SimpleUploadedFile
    
            # Set our max thumbnail size in a tuple (max width, max height)
            THUMBNAIL_SIZE = (50, 50)
    
            # Open original photo which we want to thumbnail using PIL's Image
            # object
            image = Image.open(settings.MEDIA_ROOT + self.photo.name)
    
            # Convert to RGB if necessary
            # Thanks to Limodou on DjangoSnippets.org
            # http://www.djangosnippets.org/snippets/20/
            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')
    
            # We use our PIL Image object to create the thumbnail, which already
            # has a thumbnail() convenience method that contrains proportions.
            # Additionally, we use Image.ANTIALIAS to make the image look better.
            # Without antialiasing the image pattern artifacts may result.
            image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
    
            # Save the thumbnail
            temp_handle = StringIO()
            image.save(temp_handle, 'png')
            temp_handle.seek(0)
            # Save to the thumbnail field
            suf = SimpleUploadedFile(os.path.split(self.photo.name)[-1],
                    temp_handle.read(), content_type='image/png')
            self.thumbnail.save(suf.name+'.png', suf, save=False)

        # Save this photo instance
        super(LocalPhoto, self).save()

    def get_absolute_url(self):
        return "%s%s" % (settings.LOCAL_PHOTO_URL,self.photo)
    
class SuperAlbumPhoto(TrovePhoto):
    

    
class SuperAlbum(models.Model):
    user = models.ForeignKey(User)
    album_name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=255,unique=True)
    
    def save(self, *args, **kw):
        if not self.slug:
            self.slug = slugify_uniquely(self.album_name,self.__class__)
        super(SuperAlbum, self).save(*args, **kw)
    
    def get_photos(self):
        photos = SuperAlbumPhoto.objects.filter(album=self).order_by('order')
        return photos


trove_photo = models.ForeignKey(TrovePhoto,related_name='superalbum_trove_photo')
    album = models.ForeignKey('SuperAlbum')
    order = models.IntegerField()