import sys
import array
import unittest
import Image
import time
import compress

import gameduino.prep as gdprep
from GDprep import pal555, dump, tile

def desert():
    def lerp(t, a, b):
        return a + t * (b - a)

    def clerp(t, ta, tb):
        return tuple([int(lerp(t, a, b)) for (a, b) in zip(ta, tb)])

    sky = (0,0,0)
    white = (0,0,0)
    sand = (0,0,128)
    return array.array('H', [gdprep.rgb555(*clerp(i / 31., sky, white)) for i in range(32)] + [gdprep.rgb555(*clerp(i / 31., white, sand)) for i in range(32)])

def main():
    images = ["arduino", "audio", "pcb", "raster", "snow", "video", "wireframe","gd128"]

    hh = open("../../pres.h", "w")

    pcode = ""
    for l in open("plain"):
        l = l.rstrip()
        if len(l) == 0:
            pcode += 'c'
        elif l[0] != ' ':
            if '/' in l:
                (l,im) = l.split('/')
                pcode += 'i' + chr(images.index(im))
            pcode += 't' + l + chr(0)
        else:
            pcode += 'l' + l + chr(0)
    pcode += 'r'
    dump(hh, "pres", array.array('B', pcode))
    dump(hh, "ramp", desert())


    bytes = 0
    ncol = 64
    cc = compress.Codec(b_off = 9, b_len = 3)
    for i in images:
        fn = "pres-%s.png" % i
        im = Image.open(fn)
        w,h = im.size
        (im, pal) = pal555(im, ncol)
        if 1:
            uncompressed = tile(im).tostring()
            compressed = cc.toarray(uncompressed)
            bytes += len(compressed)
            print i, len(compressed)
            compressed = array.array('B', chr(w/16) + chr(h/16) + compressed.tostring())
            dump(hh, "%s_img" % i, compressed)
        else:
            dump(hh, "%s_img" % i, tile(im))
        dump(hh, "%s_pal" % i, array.array('H', pal))
    print bytes, "bytes"
    print >>hh, "static PROGMEM prog_uchar* images[] = {"
    for i in images:
        print >>hh, "%s_pal, %s_img," % (i,i)
    print >>hh, "};"

if __name__ == '__main__':
    main()
