from django.conf import settings
from django.core.files import File
from django.core.files.base import ContentFile
from django.db import models
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import slugify
from groupsite.events.models import Event
from groupsite.settings import MEDIA_ROOT, MEDIA_URL
from os.path import join
from tempfile import *
import datetime
import django.core.files.uploadhandler
import os
import time
import zipfile

try:
    import Image
    import ImageFile
    import ImageFilter
    import ImageEnhance
except ImportError:
    try:
        from PIL import Image
        from PIL import ImageFile
        from PIL import ImageFilter
        from PIL import ImageEnhance
    except ImportError:
        raise ImportError('Photologue was unable to import the Python Imaging Library. Please confirm it`s installed and available on your current Python path.')

# Create your models here.
class Album(models.Model):
    title = models.CharField(max_length=200)
    title_slug = models.SlugField(help_text=('A "slug" is a unique URL-friendly title for an object.'))
    location = models.CharField(max_length=200)
    date = models.DateField(blank=True, help_text='Date', null=True, default=datetime.date.today())
    description = models.TextField(blank=True, max_length=2000)
    tags = models.CharField(blank=True, max_length=500)
    event= models.ForeignKey(Event, blank=True, null=True)
    zip_file = models.FileField(blank=True, upload_to="temp",
                                help_text='Select a .zip file of images to upload into a new Gallery.')
    VISIBILITY_CHIOCES = (('visible', 'Will be listed on the website'), ('not_visible', 'Will not be viewed on the website'))
    visibility = models.CharField(max_length=20, choices=VISIBILITY_CHIOCES, default='visible', blank=True)
    RESIZE_CHIOCES = (('resize', 'Will resize images to fit in slideshow'), ('no_resize', "Pictures will not be resized - Don't use this option unless you know what you're doing"))
    resize_images = models.CharField(max_length=20, choices=RESIZE_CHIOCES, default='resize', blank=True)
    
    def save(self, *args, **kwargs):
        self.title_slug = slugify(self.title)
        super(Album, self).save(*args, **kwargs)
        self.process_zipfile()
        
    def process_zipfile(self):
        if (self.zip_file.name==''):
            return
        if os.path.isfile(self.zip_file.path):
            zip = zipfile.ZipFile(self.zip_file.path)
            bad_file = zip.testzip()
            if bad_file:
                raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
            count = 1
            from cStringIO import StringIO
            for filename in sorted(zip.namelist()):
                if filename.startswith('__'): # do not process meta files
                    continue
                data = zip.read(filename)
                if len(data):
                    try:
                        # the following is taken from django.newforms.fields.ImageField:
                        #  load() is the only method that can spot a truncated JPEG,
                        #  but it cannot be called sanely after verify()
                        trial_image = Image.open(StringIO(data))
                        trial_image.load()
                        # verify() is the only method that can spot a corrupt PNG,
                        #  but it must be called immediately after the constructor
                        trial_image = Image.open(StringIO(data))
                        trial_image.verify()
                    except Exception:
                        # if a "bad" file is found we just skip it.
                        continue
                    while 1:
                        title = ''.join([self.title, str(count)])
                        slug = slugify(title)
                        try:
                            p = Photo.objects.get(title_slug=slug)
                        except Photo.DoesNotExist:
                            photo = Photo(title=filename,
                                          title_slug=slug,
                                          album=self,
                                          resize = self.resize_images
                                          )
                            photo.image.save(filename, ContentFile(data))
                            count = count + 1
                            break
                        count = count + 1
            zip.close()
            os.remove(self.zip_file.path)
    
    def __str__(self):
        return str(self.title)
    def __unicode__(self):
        return self.title
    def delete(self):
        for photo in Photo.objects.all().filter(album=self):
            photo.delete()
        os.rmdir(join(MEDIA_ROOT, 'photos', self.title_slug, 'thumbnails'))
        os.rmdir(join(MEDIA_ROOT, 'photos', self.title_slug))
        super(Album,self).delete()

def get_image_path(instance, filename):
    return os.path.join('photos', str(instance.album.title_slug), '' + time.strftime("%Y-%m-%d-") + filename)

class Photo(models.Model):
    title = models.CharField(max_length=200)
    width = models.IntegerField()
    height = models.IntegerField()
    title_slug = models.SlugField(help_text=('A "slug" is a unique URL-friendly title for an object.'))
    album = models.ForeignKey(Album, blank=True, default=get_object_or_404(Album, title='Other'))
    caption = models.TextField(blank=True, max_length=400)
    image = models.ImageField(upload_to=get_image_path, height_field='height', width_field='width')
    RESIZE_CHIOCES = (('resize', 'Will be resized to fit in slideshow'), ('no_resize', "Won't be resized - Don't use this option unless you know what you're doing"))
    resize = models.CharField(max_length=20, choices=RESIZE_CHIOCES, default='resize', blank=True)
    tags = models.CharField(blank=True, max_length=500, null=True)

    def save(self, *args, **kwargs):
        super(Photo, self).save(*args, **kwargs)
        if(self.resize=='resize'):
            self.im_resize()
        
        im = Image.open(self.image.path)
        im.thumbnail((128,128), Image.ANTIALIAS)

        path, fnext = os.path.split(self.image.name)
        fn, ext = os.path.splitext(fnext)
        thumb_path = join(MEDIA_ROOT, path, 'thumbnails/')
        if not os.path.exists(thumb_path):
            os.makedirs(thumb_path)
        im.save(thumb_path + fn + '-thumb' + ext, 'JPEG')

    def im_resize(self):
        new_image = Image.open(self.image.path)
        new_image.thumbnail((1000, 580), Image.ANTIALIAS)
        os.remove(self.image.path)
        new_image.save(self.image.path)
        
    def get_thumb(self):
        path, fnext = os.path.split(self.image.name)
        fn, ext = os.path.splitext(fnext)
        thumb_path = join(path, 'thumbnails/')
        return thumb_path + fn + '-thumb' + ext

    def get_thumb_url(self):
        return join(MEDIA_URL, self.get_thumb())

    def get_url(self):
        return join(MEDIA_URL, self.image.name)
            
    def delete(self):
        os.remove(self.image.path)
        os.remove(join(MEDIA_ROOT, self.get_thumb()))
        super(Photo,self).delete()
        
    def __str__(self):
        return self.title
    
    def __unicode__(self):
        return self.title


    # TODO(): add multimedia somewhere here.
    # TODO(): add creator and modifiers of events.
    # TODO(): add people in charge.

class ImageUploadHandler(django.core.files.uploadhandler.FileUploadHandler):
    def receive_data_chunk(self, raw_data, start):
        
        return
    def file_complete(self, file_size):
        
        return
