from typing import Tuple
from PIL import Image
import sys
import shared

TEMPLATE = """
// generated code! be nice!
#include "sys/sys.h"
sys_glyph {{ font_name }}[{{ n_glyphs }}] = { {{- glyphs|join(", ") -}} };
""".lstrip()


def main(font_name, n_glyphs, fname_png, fname_c):
    glyphs = load_glyphs(fname_png)
    assert(len(glyphs) == n_glyphs), f"must be exactly {n_glyphs} glyphs"

    with open(fname_c, "wt") as output:
        output.write(
            shared.templates.from_string(TEMPLATE).render(
                font_name=font_name,
                n_glyphs=n_glyphs,
                glyphs=glyphs,
            )
        )


def load_glyphs(fname_png: str):
    width, height, data = shared.load_image(fname_png)

    glyphs = []
    for gy in range(0, height, 8):
        for gx in range(0, width, 8):
            glyph = 0
            for py in range(0, 8):
                for px in range(0, 8):
                    x = gx + px
                    y = gy + py
                    if pixel_to_monochrome(data[y * width + x]):
                        glyph |= 1 << (py * 8 + px)
            glyphs.append(glyph)

    return glyphs


def pixel_to_monochrome(rgba: Tuple[int, int, int, int]):
    if rgba[3] < 128: return False
    if (rgba[0] + rgba[1] + rgba[2])/3 < 128: return False
    return True


if __name__ == "__main__":
    assert len(sys.argv) == 5, \
        "there must be four args (font name, n glyphs, src png, out c)"
    main(sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4])
