import os
import struct
from glob import glob


def main():
    """
    Was written to assign sixth arm vector to binary size for bootloader.
    @return:
    """

    # Parse for binaries
    file_path = file_selector("../../_bin", '*.bin')
    file_size = os.path.getsize(file_path)
    print("File size: " + str(file_size))
    size_uint32 = struct.pack("<I", file_size)
    print("File size as uint32: " + ' '.join(map('{:02X}'.format, size_uint32)))
    with open(file_path, "rb+") as file:
        # Read the first seven ARM vectors. The sixth one will be replaced.
        arm_vectors = file.read(4 * 7)
        arm_vector_6 = arm_vectors[5*4:5*4 + 4]
        print("ARM vectors: ")
        # print(''.join('{:02x}'.format(x) for x in arm_vectors))
        for x in range(0, 28, 4):
            print(' '.join(map('{:02X}'.format, arm_vectors[x:x + 4])))
        file.seek(5*4)
        file.write(size_uint32)
        file.seek(0)
        arm_vectors = file.read(4 * 7)
        print("New ARM vector: ")
        for x in range(0, 28, 4):
            print(' '.join(map('{:02X}'.format, arm_vectors[x:x + 4])))
        pass


def file_selector(path: str, pattern: str) -> str:
    result = [y for x in os.walk(path) for y in glob(os.path.join(x[0], pattern))]
    print("Files found in _bin folder: ")
    for idx, path in enumerate(result):
        print("Selection " + str(idx) + ": " + str(path))
    selection = input("Please enter desired selection [c to cancel]: ")
    while True:
        if selection == 'c':
            return ""
        if not selection.isdigit():
            selection = input("Invalid input, try again [c to cancel]: ")
        if selection.isdigit():
            if int(selection) < len(result):
                return result[int(selection)]
            else:
                selection = input("Invalid input, try again [c to cancel]: ")


if __name__ == "__main__":
    main()