#!/usr/bin/python
# -*- coding: UTF-8 -*-

import base64
from cStringIO import StringIO

from PIL import ExifTags
from flask import current_app

import config
from functions import do_encrypt_dek
import utils

def rotate_image_upon_exif( img ):
    try:
        for orientation in ExifTags.TAGS.keys():
            if ExifTags.TAGS[ orientation ] == "Orientation":
                break
        
        exif = dict( img._getexif().items() )
    
        if exif[orientation] == 3:
            img = img.rotate( 180, expand = True )
        
        elif exif[orientation] == 6:
            img = img.rotate( 270, expand = True )
        
        elif exif[orientation] == 8:
            img = img.rotate( 90, expand = True )
    
    except ( AttributeError, KeyError, IndexError ):
        pass
    
    return img

def pil2buffer( img, img_format ):
    buff = StringIO()
    img.save( buff, format = img_format )
    buff.seek( 0 )
    
    return buff

def create_thumbnail( file_uuid, img, submission_id ):
    """
        Generate a thumbnail image for a PIL image passed in argument.
    """
    current_app.logger.info( "Creating a thumbnail for the file '{}', submission '{}'".format( file_uuid, submission_id ) )
    current_app.logger.debug( "Input image: {}".format( img ) )
    
    img.thumbnail( ( 1000, 1000 ) )
    width, height = img.size
    
    current_app.logger.debug( "Thumbnail: {}".format( img ) )
    
    img_format = img.format
    buff = StringIO()
    
    if img_format == None:
        img.save( buff, format = "png" )
    elif img_format.upper() in [ "TIFF", "TIF" ]:
        img.save( buff, format = img_format, compression = "raw" )
    else:
        img.save( buff, format = img_format )
    
    img_size = buff.tell()
    buff.seek( 0 )
    
    current_app.logger.debug( "Encrypt the thumnbnail with DEK" )
    img_data = buff.getvalue()
    img_data = base64.b64encode( img_data )
    img_data = do_encrypt_dek( img_data, submission_id )
    
    current_app.logger.debug( "Saving thumnbail to database" )
    sql = utils.sql.sql_insert_generate( "thumbnails", [ "uuid", "width", "height", "size", "format", "data" ] )
    data = ( file_uuid, width, height, img_size, img.format, img_data, )
    config.db.query( sql, data )
    config.db.commit()
    
    return img
