from django.conf import settings
from PIL import Image
import os, sys

def make_thumbnail(imagefile,width=None,height=None):
    # first check that the thumbnail image doesn't already exist
    # and if it does that it's newer than the origional image
    
    base_dir = settings.MEDIA_ROOT
    thumbs_dir = base_dir
    if not thumbs_dir.endswith("/"):
        thumbs_dir = "%s/" %(thumbs_dir,)
        base_dir = "%s/" %(base_dir,)
    
    try:
        thumbs_dir = "%s%s/" %(thumbs_dir, settings.THUMBS_DIRECTORY)
        thumbsdirectory = settings.THUMBS_DIRECTORY
    except:
        thumbs_dir = "%sthumbs/" %(thumbs_dir,)
        thumbsdirectory = "thumbs"

    if width != None:
        try:
            thumb = os.stat("%sw%d/%s" % (thumbs_dir, width, imagefile))
            pic = os.stat("%s%s" % (base_dir, imagefile))
            if thumb.st_ctime < pic.st_ctime:
                # regenerate the icon
                img = Image.open("%s%s" %(base_dir, imagefile))
                (curwidth,curheight) = img.size

                newwidth = width
                newheight = int((newwidth * curheight) / curwidth)

                newimg = img.resize((newwidth, newheight))
                newimg.save("%sw%d/%s" %(thumbs_dir, width, imagefile))
                
                return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
            else:
                # we have a winner!
                return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
        except:
            # well, there's not one there. feh. sucks.
            try:
                directory_to_create = imagefile[:imagefile.rindex(os.sep)]
                img = Image.open("%s%s" %(base_dir, imagefile))
                if not os.path.isdir("%sw%d/%s" %(thumbs_dir, width, directory_to_create)):
                    os.makedirs("%sw%d/%s" %(thumbs_dir, width, directory_to_create))
                (curwidth,curheight) = img.size

                newwidth = width
                newheight = int((newwidth * curheight) / curwidth)

                newimg = img.resize((newwidth, newheight))
                newimg.save("%sw%d/%s" %(thumbs_dir, width, imagefile))
                
                return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
            except Exception as e:
                sys.stderr.write("Got exception: %s" %(e,))

    elif height != None:
        try:
            thumb = os.stat("%sh%d/%s" % (thumbs_dir, height, imagefile))
            pic = os.stat("%s%s" % (base_dir, imagefile))
            if thumb.st_ctime < pic.st_ctime:
                # regenerate the icon
                img = Image.open("%s%s" %(base_dir, imagefile))
                (curwidth,curheight) = img.size

                newheight = height
                newheight = int((newheight * curwidth) / curheight)

                newimg = img.resize((newwidth, newheight))
                newimg.save("%sh%d/%s" %(thumbs_dir, height, imagefile))
                
                return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
            else:
                # we have a winner!
                return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
        except:
            # well, there's not one there. feh. sucks.
            try:
                directory_to_create = imagefile[:imagefile.rindex(os.sep)]
                img = Image.open("%s%s" %(base_dir, imagefile))
                os.makedirs("%sh%h/%s" %(thumbs_dir, height, directory_to_create))
                (curwidth,curheight) = img.size

                newheight = height
                newwidth = int((newheight * curwidth) / curheight)

                newimg = img.resize((newwidth, newheight))
                newimg.save("%sh%d/%s" %(thumbs_dir, height, imagefile))
                
                return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
            except:
                pass

    # if everything fails, we'll return the origional image URL
    # this is for simpilicity
    return "%s%s" %(settings.MEDIA_URL, imagefile)

