# Some image experiments

from PythonLabs.Canvas import *

def string_to_ints(s):
    # convert a line of ppm pixel data to a list of ints
    s = s.split(" ")
    s2 = []
    for token in s:
        if len(token) > 0 and token[0].isdigit():
            s2.append(int(token))
    return s2


def read_ppm(filename):
    # parse an image as a 3d array: result[r][c][rgb] is
    # the value of row r, column c, where rgb is 0, 1, or 2
    # to select red, green, or blue
    inf = open(filename, "r")
    file_type = inf.readline()
    if file_type != "P3\n":
        return None
    image_size = string_to_ints(inf.readline())
    image_width = image_size[0]
    image_height = image_size[1]
    pixel_range = string_to_ints(inf.readline())[0]
    pixels = inf.readline()
    ints = []
    row = []
    image = []
    while len(pixels) > 0:
        ints = ints + string_to_ints(pixels)
        i = 0
        while i < len(ints) - 2:
            pixel = ints[i : i + 3]
            row.append(pixel)
            if len(row) >= image_width:
                image.append(row)
                row = []
            i += 3
        ints = ints[i : ]
        pixels = inf.readline()
    return image    

def start_image(size):
    # create a canvas and call image_test()
    Canvas.init(size, size, "Image")
    Canvas.Rectangle(1, 1, size + 1, size + 1, fill="white", outline = "white")
#    image_test(size)

def hex2(i):
    # hex2 is a helper function for hexcolor and draw_image
    # convert to hex, remove '0x' prefix, insert leading zero, trim to length 2
    return ('0' + (hex(i)[2 : ]))[-2 : ]

def hexcolor(color):
    # hexcolor converts a list [r, g, b] to a color string, "#rrggbb"
    return '#' + hex2(color[0]) + hex2(color[1]) + hex2(color[2])

def draw_image(image, x, y, scale = 1):
    # draw image at location x,y with optional integer scale factor
    for r in range(len(image)):
        for c in range(len(image[0])):
            color = hexcolor(image[r][c])
            Canvas.Rectangle(x + c * scale, y + r * scale,
                             x + (c + 1) * scale, y + (r + 1) * scale,
                             outline = color, fill = color)

def image_test(size):
    # display nautical.ppm, assumes canvas exists
    image = read_ppm("nautical.ppm")
    draw_image(image, 0, 0, scale = 1)

# start_image(250)
