import Image, ImageDraw, ImageFont
import gameduino.prep as gdprep

# im = Image.open("scroll.png")
# CELL=16

im = Image.open("miniscroll.png")
CELL=32

(picd, chrd, pald) = gdprep.encode(im)

im = im.resize((im.size[0] * CELL/8, im.size[1] * CELL/8))
im.save("p0.png")

ov = Image.new("RGB", im.size)
dr = ImageDraw.Draw(ov)
font = ImageFont.truetype("/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType/Times_New_Roman_Bold.ttf", CELL*13/16)
xys = [(x,y) for y in range(im.size[1] / CELL)
             for x in range(im.size[0] / CELL)]
assert len(xys) == len(picd)
cc = (255,255,255)
tiles = [None for i in range(max(picd)+1)]
for tile,(x,y) in zip(picd, xys):
    (w,h) = font.getsize(str(tile))
    dr.text((CELL*x + (CELL/2)-w/2, CELL*y+3), str(tile), font=font, fill=cc)
    tiles[tile] = im.crop((CELL*x,CELL*y,CELL*x+(CELL),CELL*y+(CELL)))
for x in range(im.size[0] / CELL):
    dr.line([(CELL*x,0), (CELL*x,im.size[1])], fill=(128,128,128))
for y in range(im.size[1] / CELL):
    dr.line([(0, CELL*y), (im.size[1], CELL*y)], fill=(128,128,128))
ov.save("p1.png")

tm = Image.new("RGB", im.size, (255,255,255))
dr = ImageDraw.Draw(tm)
for i,t in enumerate(tiles):
    x = 20 + 3 * CELL*(i / 10)
    y = 20 + 40*(i % 10)
    dr.text((x,y+4), str(i), font=font, fill=(0,0,0))
    tm.paste(t, (x + CELL,y))
    dr.line([(x+CELL,y),(x+2*CELL,y), (x+2*CELL,y+CELL), (x+CELL,y+CELL), (x+CELL,y)], fill=(0,0,0))
tm.save("p2.png")
