#!/usr/bin/python3

import gzip
import struct
import qrcode
import sys
from jdsu.qrcodegen.json_parser import get_json_lite
import subprocess

QR_CODE_LIMIT = 900


def format_copy_gzip(filename):
    with open(filename,'rb') as tinput:
        data = tinput.read().decode('utf8').replace("'", '"')  # from bytes to str
        data = get_json_lite(data)
        data = data.replace("'",'"').encode('utf8')  # from str to bytes
        raw = gzip.compress(data)
        return raw


def direct_copy_gzip(filename):
    with open(filename,'rb') as tinput:
        data = tinput.read()
        raw = gzip.compress(data)
        return raw


format_functions = {
    0: (direct_copy_gzip, 0),
    1: (format_copy_gzip, 0)
}


def transform(filename, ftype, output):
    data = format_functions[ftype][0](filename)
    blobs = [data[i:i+QR_CODE_LIMIT] for i in range(0, len(data), QR_CODE_LIMIT)]
    cnt = len(blobs)
    files = [""] * cnt

    for nr in range(cnt):
        opt = bytes([(cnt << 4) | (nr + 1)])
        header = struct.pack('cc', bytes([format_functions[ftype][1]]), opt)
        encodedBytes = header + blobs[nr]

        qr = qrcode.QRCode(
            version=None,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(encodedBytes)
        qr.make(fit=True)
        print("QRCODE version:%i" % qr.version)
        img = qr.make_image(fill_color="black", back_color="white")
        filename = "%s_%i_%i.png"%(output, nr, cnt - 1)
        print(filename)
        files[nr] = filename
        with open(filename, "wb") as out:
            img.save(out)

    return files


# qrcodegen <inputfile> [<format>] [<output_prefix>]
if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
        print("Usage:\n\t%s <inputfile> [<format>] [<output_prefix>]"%sys.argv[0])
        for i,f in format_functions.items():
            print("Format:\n\t%i: %s"%(i,f.__name__))
        exit(2)

    format = 0
    if len(sys.argv) >= 3:
        format = int(sys.argv[2].strip())

    output = "./output"
    if len(sys.argv) >= 4:
        output = sys.argv[3].strip()
        
    files = transform(sys.argv[1], format, output)

    exe = "/usr/bin/qrcodeviewer"
    files = ["file://" + file for file in files]

    subprocess.run([exe, *files])
