from django.db import models
from django.conf import settings
import datetime
import os.path
from django.template.defaultfilters import escape
from django.core.urlresolvers import reverse

PRIVACY_LEVELS = (
    (0, 'Private'),
    (1, 'Public'),
)


def get_image_file_path(instance, filename):
    "Calculate a storage path for this file instance"
    parts = [instance.owner.username]
    today = datetime.datetime.utcnow()
    parts.extend(map(unicode, [today.year, today.month]))
    parts.append(os.path.basename(filename))
    path = u"/".join(parts)
    return path


# Create your models here.
class Photo(models.Model):
    image = models.ImageField(
        upload_to=get_image_file_path,
        height_field='height',
        width_field='width',
    )
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    height = models.PositiveSmallIntegerField(default=0, editable=False)
    width = models.PositiveSmallIntegerField(default=0, editable=False)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    date_uploaded = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    access = models.IntegerField(choices=PRIVACY_LEVELS)
    size = models.PositiveIntegerField(default=0, editable=False)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.size = self.image.size
        super(Photo, self).save(*args, **kwargs)

    # def size(self):
    #     return self.image.size

    def user_link(self):
        return '<a href="%s">%s</a>' % (
            reverse(
                "admin:imagr_users_imagruser_change",
                args=(self.owner.id, )
                ),
            escape(self.owner)
        )
    user_link.allow_tags = True
    user_link.short_description = "Owner"


class Album(models.Model):
    title = models.CharField(max_length=100)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    description = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    access = models.IntegerField(choices=PRIVACY_LEVELS)
    photos = models.ManyToManyField(Photo)
    cover_photo = models.ForeignKey(Photo, related_name="host_album")

    def __unicode__(self):
        return self.title

    def user_link(self):
        return '<a href="%s">%s</a>' % (
            reverse(
                "admin:imagr_users_imagruser_change",
                args=(self.owner.id, )),
            escape(self.owner)
        )

    # def was_created_in_range(date1, date2):
      #  return date2 >= self.date_created >= date1

    user_link.allow_tags = True
    user_link.short_description = "Owner"
