from thumbs import ImageWithThumbsFieldFile
from thumbs import ImageWithThumbsField
import cStringIO
from PIL import Image, ImageDraw, ImageFont
from django.core.files.base import ContentFile
from math import atan, degrees

def unify_size(img, size, format):
    
    img.seek(0)
    image=Image.open(img)

    if image.mode not in ('L', 'RGB', 'RGBA'):
        image = image.convert('RGB')
    size_w, size_h=size
    xsize, ysize = image.size
    tmp_h=int(size_w/(float(xsize)/ysize))
    if tmp_h>size_h:
        size_w=int(size_h/(float(ysize)/xsize))
    else:
        size_h=tmp_h
       
    image2=image.resize((size_w, size_h))
    io = cStringIO.StringIO()

    image2.save(io, format)
    return ContentFile(io.getvalue())

def add_watermark(img, text, format="JPEG"):
    
    def getfontsize(text, max_size):
        size=0    
        width=0
        while width<max_size:
            size+=1
            font=ImageFont.truetype("arial.ttf", size)
            width, height = font.getsize(text)
        return (size-1)
        
    img.seek(0)
    image=Image.open(img)
    watermark = Image.new("RGBA", (image.size[0], image.size[1]))
    draw = ImageDraw.ImageDraw(watermark, "RGBA")
    
    print "Def size"
    #define size of text
    fontsize=getfontsize(text, watermark.size[0])
    font=ImageFont.truetype("arial.ttf", fontsize)
    draw.setfont(font)
    text_width, text_height = font.getsize(text)

    print "write text"
    #write text
    draw.text((0,(watermark.size[1]-text_height)/2), text)
    print "rotate"
    #roteate
    watermark = watermark.rotate(degrees(atan(float(image.size[1])/ image.size[0])), Image.BICUBIC)
    print "make transparent"
    #make transparent
    mask = watermark.convert("L").point(lambda x: min(x, 55))
    watermark.putalpha(mask)
    print "merge images"
    #merge images
    image.paste(watermark, None, watermark)

    #save in output stream
    print "save1"
    print "format:="+format
    io = cStringIO.StringIO()
    print "format:="+format
    image.save(io, format)
    print "after save"
    image.save(io, format)
    return ContentFile(io.getvalue())

class ExtImageFieldFile(ImageWithThumbsFieldFile):
    def getFileFormat(self, name):
        split = name.rsplit('.',1)
        format=split[1]
        if format.upper()=='JPG':
            format = 'JPEG'
        return format
    def save(self, name, content, save=True):
        format=self.getFileFormat(name)
        if self.field.max_size:           
            content=unify_size(content, self.field.max_size, format)
        #if self.field.watermark:
            #content=add_watermark(content, self.field.watermark, format)
        super(ExtImageFieldFile, self).save(name, content, save)

class ExtImageField(ImageWithThumbsField):
    attr_class = ExtImageFieldFile
    def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, sizes=None, max_size=None, watermark=None, **kwargs):
        self.max_size=max_size
        self.watermark=watermark
        super(ExtImageField, self).__init__(verbose_name, name, width_field, height_field, sizes, **kwargs)    