"""
decode a single binary frame
"""

from __future__ import print_function

import argparse
import json

from satnogsdecoders import decoder


def decode_frame(decoder_name, raw_frame):
    """
    decoding function
    """

    decoder_class = getattr(decoder, decoder_name.capitalize())
    frame = decoder_class.from_bytes(raw_frame)

    fields = decoder.get_fields(frame, empty=False)
    return fields


def main():
    """
    main entry point
    """

    parser = argparse.ArgumentParser(
        description='Decode a raw frame with the selected decoder'
        '(generated by Kaitai) and print its json representation.')
    parser.add_argument('decoder_name',
                        type=str,
                        help='name of the decoder (e.g. siriussat)')
    parser.add_argument('raw_frame_file',
                        type=str,
                        help='Path to the file containing the raw frame')
    args = parser.parse_args()

    # Load the raw frame
    with open(args.raw_frame_file, 'rb') as rawfile:
        raw_frame = rawfile.read()

    fields = decode_frame(args.decoder_name, raw_frame)
    print(json.dumps(fields, indent=4, sort_keys=False))
