'''
Some functions to help work with Images.

There is NO need to modify this file.

Created on Sep 2, 2013

@author: rcd
'''
import tkFileDialog
import os
import Image


def getFile (filename=''):
    '''
    gets a file for processing
    files can come from a variety of sources:
    - internet, via URL
    - local computer, via file name
    - local computer, chosen by the user
    '''
    if filename == '':
        return tkFileDialog.askopenfile(initialdir=os.getcwd(), mode='rb')
    else:
        return open(filename, 'rb')


def openImage (filename=''):
    '''
    opens the given image and converts it to RGB format
    returns a default image if the given one cannot be opened
    filename is the name of a PNG, JPG, or GIF image file
    '''
    image = Image.open(getFile(filename))
    if image == None:
        print("Specified input file " + filename + " cannot be opened.")
        return Image.new("RGB", (400, 400))
    else:
        print(str(image.size) + " = " + str(len(image.getdata())) + " total pixels.")
        return image.convert("RGB")


def applyFilter(image, transform):
    '''
    transform each pixel in the given image using the given transform
    image is an open Image object
    transform is a function to apply to each pixel in image
    '''
    def wrapper (f):
        if f.func_code.co_argcount == 1:
            return lambda p: (f(p[0]),f(p[1]),f(p[2]))
        elif f.func_code.co_argcount == 3:
            return lambda p: (f(*p),f(*p),f(*p))
    pixels = [ wrapper(transform)(p) for p in image.getdata() ]
    image.putdata(pixels)
    return image


def showTransformedImage(filename='', *transforms):
    '''
    displays the given image after if has been transformed by the given transform
    filename is the name of a PNG, JPG, or GIF image file
    transform is a function to apply to each pixel in image
    '''
    # load image and get data to manipulate
    image = openImage(filename)
    # modify image by applying variety of filters
    for t in transforms:
        image = applyFilter(image, t)
    # show results
    # to work around a Windows 7 bug --- must refresh Eclipse project to see
    image.save("transform_results.png")
    # for everyone else (may still raise an error to appear on Windows :(
    image = openImage("transform_results.png")
    image.show()
