import framebuf
import pbm
import math
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("pbm_image_file", help="PBM fotmat mono image.", type=argparse.FileType("rb"))
    parser.add_argument("img_name", help="generated image name.")
    args = parser.parse_args()
    img_name = args.img_name.upper().replace("-", "_").replace(" ", "_").replace(".", "_")
    iw, ih, _fmt, data, _ = pbm.read_image(args.pbm_image_file)
    img = framebuf.FrameBuffer(data, iw, ih, framebuf.MONO_HLSB)
    buffer_frame = bytearray(iw * math.ceil(ih / 8))
    frame = framebuf.FrameBuffer(buffer_frame, iw, ih, framebuf.MONO_VLSB)
    for y in range(ih):
        for x in range(iw):
            frame.pixel(x, y, img.pixel(x, y))

    data = bytearray()
    data.append(iw - 1) # image width - 1
    data.append(ih - 1) # image height - 1
    data.extend(buffer_frame) # image data in MONO_VLSB format
    f = open(f"img_{img_name.lower()}.h", "wt")
    f.write("#pragma once\n")
    f.write("#include <stdint.h>\n")
    f.write("\n")
    f.write(f"const uint8_t IMG_{img_name}[] = {{")
    for i, byte in enumerate(data):
        if i % 16 == 0:
            f.write("\n   ")
        f.write(f" 0x{byte:02X},")
    f.write("\n};\n")
    f.write(f"const uint32_t DATA_SIZE_IMG_{img_name} = {len(data)};\n")
    f.write("\n")
    f.close()

    print(f"Image Name: {img_name}")
    print(f"Header File Name: img_{img_name.lower()}.h")