import adtf_file
import os

adtf_runtime_dir = os.environ["adtf_runtime_DIR"]


def dump_stream_type(stream_type, indent="      "):
    print(indent + f'stream_meta_type: {stream_type.meta_type}')
    substreams = stream_type.substreams
    if len(substreams) == 0:
        print(indent + f'properties:')
        for name, value in stream_type.properties.items():
            print(indent + f'  {name}: {value.value}')
    else:
        print(indent + f'substreams:')
        for name, substream in substreams.items():
            print(indent + f'  {name}:')
            print(indent + f'    id: {substream.id}')
            dump_stream_type(substream.stream_type, indent + "    ")


def dump_file(filename):
    reader = adtf_file.create_reader(filename)

    print('header:')
    print(f'  version: {reader.file_version}')
    # this segfaults, potentially because of ABI issues with std::optional
    # print(f'  item_count: {reader.item_count}')
    print(f'  description: {reader.description}')

    print('extensions:')
    for extension in reader.extensions:
        print(f'  {extension.name}:')
        print(f'    stream_id: {extension.stream_id}')
        print(f'    user_id: {extension.user_id}')
        print(f'    type_id: {extension.type_id}')
        print(f'    version_id: {extension.version_id}')
        print(f'    data: {bytearray(extension).hex(" ")}')

    print('streams:')
    for stream in reader.streams:
        print(f'  {stream.name}:')
        print(f'    stream_id: {stream.stream_id}')
        print(f'    item_count: {stream.item_count}')
        print(f'    timestamp_of_first_item: {stream.timestamp_of_first_item}')
        print(f'    timestamp_of_last_item: {stream.timestamp_of_last_item}')
        print(f'    streamtype:')
        dump_stream_type(stream.initial_type)

    print('items:')
    item_index = 0
    while True:
        item = reader.get_next_item()

        if not item:
            break

        print(f'  {item_index}:')
        print(f'    time_stamp: {item.time_stamp}')
        print(f'    stream_id: {item.stream_id}')
        print(f'    type: {item.type}')

        if item.type == adtf_file.ItemType.Sample:
            sample = item.sample
            print(f'    sample:')
            print(f'      time_stamp: {sample.time_stamp}')
            print(f'      substream_id: {sample.substream_id}')
            print(f'      flags: {sample.flags}')
            print(f'      buffer: {bytearray(sample.buffer).hex(" ")}')

        if item.type == adtf_file.ItemType.StreamType:
            print(f'    stream type:')
            dump_stream_type(item.stream_type)

        if item.type == adtf_file.ItemType.Trigger:
            print(f'    trigger')

        item_index = item_index + 1

    return item_index


def test_dump_content():
    assert (dump_file(adtf_runtime_dir + "/examples/demo_adtfdat_files/example_file.adtfdat") == 1469)
