#!/usr/bin/env python3

# pylint: disable=wrong-import-position

"""Test the low level interface to odirectcmodule."""

import os
import sys
sys.path.insert(0, '.')

import odirectcmodule  # noqa: ignore=E402


def my_hex(character):
    """Convert character to hexadecimal string."""
    ordinal = ord(character)
    string = hex(ordinal)
    string2 = string[2:]
    if len(string2) == 1:
        string2 = '0' + string2
    return string2


def hex_dump(string):
    """Hex dump a string."""
    numch = 0
    for character in string:
        if character in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+\\|'\"[]{}":
            sys.stdout.write("%s " % character)
        else:
            sys.stdout.write(my_hex(character))
        numch += 1
        if numch == 60:
            print()
            numch = 0


def main():
    """Test odirectcmodule, main function."""
    buffer_ = odirectcmodule.create_odirect_buffer()
    odirectcmodule.odirect_aligned_malloc(1 << 18, 1 << 18, buffer_)

    for filename in (os.fsencode(argument) for argument in sys.argv[1:]):
        file_descriptor = odirectcmodule.odirect_open(filename, b'rbd')
        if file_descriptor < 0:
            sys.stderr.write('Opening %s failed\n' % filename)
            sys.exit(1)
        blockno = 0
        while True:
            byte_string = odirectcmodule.odirect_pull(file_descriptor, buffer_)
            # print('fred 1: read byte_string[:10]: {}'.format(byte_string[:10]))
            sys.stdout.flush()
            if not byte_string:
                break
            blockno += 1
        retval = odirectcmodule.odirect_close(file_descriptor)

    odirectcmodule.odirect_aligned_free(buffer_)
    retval = odirectcmodule.destroy_odirect_buffer(buffer_)

    # This was missing for a long time...
    sys.exit(retval)


main()