#!/usr/bin/env python3


import sys

from PIL import Image
from pathlib import Path

def get_bit(im, x, y):
    px = im.getpixel((x, y))

    if px == 0 or px == (0, 0, 0, 255):
        return 0
    if px == 1 or px == (255, 255, 255, 255):
        return 1
    print(x, y)
    print(px)
    raise

def generate_bitmap_from_gif(file: Path, fd):
    variable_name = file.with_suffix("").name

    im = Image.open(file)
    (w, h) = im.size

    assert w % 8 == 0

    fd.write(f"static const uint16_t PROGMEM {variable_name}_dims[] = {{{w}, {h}, {im.n_frames}}};\n")
    fd.write(f"static const uint8_t PROGMEM {variable_name}[][{w * h // 8}] = {{\n")
    for i in range(im.n_frames):
        im.seek(i)
        fd.write("  {\n")
        for y in range(h):
            line = []
            for x in range(0, w, 8):
                byte_str = "".join(str(get_bit(im, x + i, y)) for i in range(8))
                byte = int(byte_str, 2)
                line.append(f"0x{byte:02x}")
            line_str = ", ".join(line)
            fd.write(f"    {line_str},\n")
        fd.write("  },\n")
    fd.write("};\n")

if __name__ == "__main__":
    generate_bitmap_from_gif(Path("./animations/spinny.gif"), sys.stdout)
    generate_bitmap_from_gif(Path("./animations/tiny_train.gif"), sys.stdout)