#!/usr/bin/env python3

import math
import PIL
from PIL import Image

def line(w, h=1):
    out = [0x1d, 0x76, 0x30, 0x00]
    out += [math.ceil(w/8), (w//8)//256]
    out += [h%256, h//256]
    print(w,h,out)

    data = [0xFF]*(w//8)
    last = 0
    for i in range(w%8):
        last += 2**(7-i)
    if last != 0:
        data.append(last)

    print(len(data))

    for i in range(h):
        out += data

    print(len(out))

    return bytes(out)

def size_for_printer(w,h):
    return [math.ceil(w/8), (w//8)//256, h%256, h//256]

def print_image(filename):
    img = Image.open(filename)
    w, h = img.size
    needs_resize = False
    if w>576:
        f = 576/w
        nw = int(w*f)
        nh = int(h*f)
        needs_resize=True

    img = img.convert("1")
    if needs_resize:
        img = img.resize((nw, nh), PIL.Image.NEAREST)

    data = [0x1d, 0x76, 0x30, 0x00] + size_for_printer(*img.size)
    for y in range(img.height):
        current_byte = 0
        current_bit = 0
        for x in range(img.width):
            l = img.getpixel((x, y))
            to_add = 1<<(7-current_bit)
            current_byte += to_add if l<127 else 0
            current_bit += 1
            if current_bit>7:
                data.append(current_byte)
                current_bit = 0
                current_byte = 0
        if current_bit != 0:
            data.append(current_byte)
    return bytes(data)

def main():
    with open("/dev/usb/lp1", "wb") as lp:
        lp.write(bytes([0x1b, 0x40]))
        lp.write(bytes([0x1b, 0x74, 0x06]))
        lp.write("  0123456789ABCDEF0123456789ABCDEF".encode("latin-1"))
        lp.write(bytes([13,10]))
        for offs in range(7):
            lp.write((hex(2+2*offs)[-1]+" ").encode("latin-1"))
            for c in range(32):
                lp.write(bytes([(1+offs)*0x20+c]))
            lp.write(bytes([13,10]))
        #lp.write("Hier kommt ein ".encode("latin-1"))
        #lp.write(print_image("inline.bmp"))
        #lp.write("-Emoji".encode("latin-1"))
        #lp.write(bytes([0x0d, 0x0a]))
        
        #lp.write(print_image("test6.bmp"))
        #lp.write(bytes([0x0d, 0x0a]))
        lp.write(bytes([0x1d, 0x56, 0x42, 25]))
        lp.flush();

if __name__ == "__main__":
    main()
