'''
Screen dimensions:
296x
128y

https://www.thonky.com/qr-code-tutorial

first get numeric mode (mode 1) figured out, then expand to different modes
mode indicator needs to be 4 bits long

start with version 1 (21x21 px), then go up in density
character count indicator for version 1 needs to be 9 bits long

start with lowest error correction

define binary value with specific length:
    '{0:0<length>b}'.format(value)
'''

import ugfx
ugfx.init()

def clearScreen(amount = 1):
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    for x in range(0, amount):
        ugfx.clear(ugfx.BLACK)
        ugfx.flush()
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()

def encodeQrNumeric():
    global qrValue

    # split into groups of 3
    splitGroups = [qrValue[i:i+3] for i in range(0, len(qrValue), 3)]
    # convert each group to binary and merge them into a new string
    binString = ''
    for i in splitGroups:
        binString += '{0:0b}'.format(int(i))
    return binString


def encodeQrValue():
    global qrMode
    global characterCount
    global qrValue

    # format qrMode
    qrModeBinString = '{0:04b}'.format(qrMode)

    # get character count
    formatString = '{0:0'+str(characterCount)+'b}'
    characterCountBinString = formatString.format(len(qrValue))

    if qrMode == 1:
        qrValueBinString = encodeQrNumeric()

    # concatenate all bin strings
    encodedData = qrModeBinString+characterCountBinString+qrValueBinString

    # add terminator zeroes to encodedData
    # needs to be 4 bits at most, or the needed amount of bits to reach requiredDataBits
    if requiredDataBits-len(encodedData) > 3:
        encodedData += '0000'
    else:
        for i in range(0, requiredDataBits-len(encodedData)):
            encodedData += '0'

    # add padding zeroes to make total length a multiple of 8
    while len(encodedData) % 8 != 0:
        encodedData += '0'

    # add padding bytes if length is still too short
    paddingBytes = ['11101100', '00010001']
    paddingBytesIndex = 0
    while requiredDataBits > len(encodedData):
        encodedData += paddingBytes[paddingBytesIndex]
        paddingBytesIndex = 1 - paddingBytesIndex

    # TODO pick up things starting at error correction coding
    #https://www.thonky.com/qr-code-tutorial/error-correction-coding

    return encodedData

clearScreen()

qrValue = '01189998819991197253'
qrMode = 1
qrVersion = 1
characterCount = 9
requiredDataBits = 19*8
encodeQrValue()