from django.db import models
from app.models import ItfModel
from ox.django.fields import DictField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core.files.base import ContentFile
from sorl.thumbnail import get_thumbnail

class GalleryAlbum(ItfModel):
    '''
    
    '''
    title = models.CharField(max_length=512)
    #slug = models.SlugField(unique=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.title

    def get_edit_url(self):
        return '/mediagallery/edit/%d' % self.id

    def get_absolute_url(self):
        return '/mediagallery/view/%d' % self.id

    def thumbnail(self):
        if Photo.objects.filter(album=self).count() == 0:
            return None
        return Photo.objects.filter(album=self)[0].image        

    def get_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'photos': Photo.objects.filter(album=self),
            'videos': YoutubeVideo.objects.filter(album=self),
            'links': GalleryLink.objects.filter(album=self)
        }

    def get_json(self):
        return {
            'photos': [p.get_dict() for p in Photo.objects.filter(album=self)],
            'videos': [y.get_dict() for y in YoutubeVideo.objects.filter(album=self)],
            'links': [l.get_dict() for l in GalleryLink.objects.filter(album=self)]
        }        


class GalleryItem(models.Model):
    title = models.CharField(max_length=512, blank=True, null=True)
    done = models.BooleanField(default=False)
    album = models.ForeignKey(GalleryAlbum)
    data = DictField(default={})    

    def __unicode__(self):
        return self.title


class Photo(GalleryItem):
    image = models.ImageField(upload_to="upload/mediagallery/images", blank=True, null=True) #FIXME: upload to better place, with galleries having folders

    def save_chunk(self, chunk, name='data.bin'):
        if not self.done:
            if not self.image:
                self.image.save(name, ContentFile(chunk))
                self.title = name
                self.save()
            else:
                f = open(self.image.path, 'a')
                f.write(chunk)
                f.close()
            return True
        return False

    def get_thumbnail(self, size='100x100'):
        return get_thumbnail(self.image, size).url

    def get_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'thumb640': self.get_thumbnail(size='640')
        } 


class YoutubeVideo(GalleryItem):
    youtube_id = models.CharField(max_length=64)

    def __unicode__(self):
        return self.title

    def thumbnail(self):
        return "http://i.ytimg.com/vi/%s/default.jpg" % self.youtube_id

    def iframe(self):
        return '<iframe width="560" height="315" src="http://www.youtube.com/embed/%s" frameborder="0" allowfullscreen></iframe>' % self.youtube_id

    def get_dict(self):
        return {
            'id': self.id,
            'youtube_id': self.youtube_id,
            'thumbnail': self.thumbnail(),
            'iframe': self.iframe()
        }


class GalleryLink(GalleryItem):
    url = models.URLField(verify_exists=False, max_length=1024)
    
    def get_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'url': self.url
        }

#class Video(GalleryItem):
#    ...


#class YoutubeVideo(GalleryItem):
#    ...




# Create your models here.
