import time
from typing import IO
from common import *


def decode_frame(f: IO[bytes], last_frame: list[list[bool]]) -> list[list[bool]]:
    pixels = []
    while len(pixels) < res[0]*res[1]:
        count = int.from_bytes(f.read(1), "little")
        # high bit stores value
        val = bool(count & 1)
        cnt = count >> 1
        for _ in range(cnt):
            pixels.append(val)
    # reshape to res
    pixels = [pixels[i:i+res[0]] for i in range(0, len(pixels), res[0])]
    
    # apply diff
    if last_frame:
        pixels = diff(last_frame, pixels)
    return pixels

def run_encoded():
    f = open("out_diff.bin", "rb")
    last_frame = None
    while True:
        t1 = time.time()
        pixels = decode_frame(f, last_frame)
        if len(pixels) == 0:
            break
        last_frame = pixels
        print_frame(pixels)
        t2 = time.time()
        time.sleep(1/24 - (t2-t1))

if __name__ == "__main__":
    run_encoded()