# -*- coding: utf-8 -*-

import os

from django.db import models
from django.utils.translation import ugettext as _
from pilkit.processors import ResizeToFill, ResizeToFit, SmartResize, Transpose
from imagekit.exceptions import MissingSource
from imagekit.models import ImageSpecField
import imagekit


CHOICES_HORIZONTAL = (
    (0.00000001, _('left')),
    (0.5, _('center')),
    (1, _('right'))
)

CHOICES_VERTICAL = (
    (0.00000001, _('top')),
    (0.5, _('middle')),
    (1, _('bottom'))
)


class ArticleImage(imagekit.ImageSpec):
    format = 'JPEG'
    width = 200
    height = 120
    processors = [ResizeToFill(width=200, height=120, anchor=(0, 0.5))]


class CalloutImage(imagekit.ImageSpec):
    format = 'JPEG'
    width = 941
    height = 300

    @property
    def processors(self):
        model, field_name = imagekit.utils.get_field_info(self.source)
        anchor = model.get_anchor()
        if anchor:
            return [Transpose(), ResizeToFill(
                width=self.width,
                height=self.height, anchor=anchor
            )]
        else:
            return [Transpose(), SmartResize(
                width=self.width,
                height=self.height
            )]


class DisplayImage(imagekit.ImageSpec):
    format = 'JPEG'
    processors = [Transpose(),
                  ResizeToFit(width=940, height=940, upscale=False)]


class ThumbnailImage(CalloutImage):
    format = 'JPEG'
    width = 140
    height = 140


imagekit.register.generator('kasu:image:article', ArticleImage)
imagekit.register.generator('kasu:image:callout', CalloutImage)
imagekit.register.generator('kasu:image:display', DisplayImage)
imagekit.register.generator('kasu:image:thumbnail', ThumbnailImage)


class ImageModel(models.Model):
    article = ImageSpecField(source='image', id='kasu:image:article')
    callout = ImageSpecField(source='image', id='kasu:image:callout')
    display = ImageSpecField(source='image', id='kasu:image:display')
    thumbnail = ImageSpecField(source='image', id='kasu:image:thumbnail')

    class Meta:
        abstract = True

    def get_anchor(self):
        try:
            anchor_horizontal = getattr(self, 'anchor_horizontal')
            anchor_vertical = getattr(self, 'anchor_vertical')
        except AttributeError:
            return None
        if anchor_horizontal and anchor_vertical:
            return self.anchor_horizontal, self.anchor_vertical
        else:
            return None


def regenerate_image_cache(sender, instance=None, created=False, raw=False,
                           **kwargs):
    """
    Reganerate the images.
    """
    if instance.image:
        print instance.image 
        print instance.display
        print instance.callout
        for cached_image in (instance.article, instance.callout, instance.display, instance.thumbnail):
            try:
                os.remove(cached_image.path)
            except OSError:
                pass
