import os
from PIL import Image
import sys
import glob

def readHumanFile(fileName):
    with open(fileName, "r") as file:
        data = file.read().split("\n")
        data = [d.strip() for d in data if len(d) > 0]
        cmdBytes = []
        for d in data:
            cmdBytes.extend(bytes.fromhex(d))
        return cmdBytes

def readFile(fileName):
    with open(fileName, "rb") as file:
        cmdBytes = [file.read()]
        return cmdBytes

def decodeCommands(cmdBytes, saveFilename=None):
    cmds = []

    idx = -1
    data = []
    cmdCode = 0x00
    dataLen = 0
    crc = 0x00
    for i, b in enumerate(cmdBytes):
        idx += 1
        #print(i, idx, hex(b))
        if b == 0x51 and idx == 0:
            pass
        elif b == 0x78 and idx == 1:
            pass
        elif idx == 2:
            cmdCode = b
        elif b == 0x00 and idx == 3:
            pass
        elif idx == 4:
            dataLen = b
        elif idx == 5:
            if b != 0:
                dataLen = dataLen*0x100 + b
        elif idx >= 6 and idx < 6+dataLen:
            data.append(b)
        elif idx == 6+dataLen:
            crc = b
        elif idx == 6+dataLen+1 and b == 0xFF:
            o = {
                "cmd": cmdCode,
                "data": data,
                "crc": crc
            }
            cmds.append(o)
            idx = -1
            crc = 0
            data = []
            cmdCode = 0
        else:
            idx = -1
            crc = 0
            data = []
            cmdCode = 0
    #print(cmds)
    #for c in cmds:
    #    print(hex(c["cmd"]), hex(len(c["data"])), hex(c["crc"]))

    rows = []
    for c in cmds:
        if c["cmd"] == 0xa2:
            s = "".join([bin(b)[2:10].zfill(8)[::-1] for b in c["data"]]) 
            row = [int(x)==1 for x in s]
            rows.append(row)
        elif c["cmd"] == 0xbf:
            row = []
            for b in c["data"]:
                bit = (b & (1<<7)) == 128
                times = b & ~(1<<7)
                row.extend([bit] * times)
            rows.append(row)

    HEIGHT = len(rows)
    WIDTH = max(len(r) for r in rows)

    img = Image.new("1", (WIDTH, HEIGHT))
    for y in range(HEIGHT):
        for x in range(WIDTH):
            img.putpixel((x,y), not rows[y][x])

    if saveFilename != None:
        img.save(saveFilename)

    return img