#!/usr/bin/env python3

import base64
import pmt
import json
import signal
from zmq_subs.helper_functions.zmq_create_context import open_sub_socket
from zmq_subs.helper_functions.date_helpers import get_current_utc_time_str
from zmq_subs.helper_functions.parsers import prefix_path_parser
from zmq_subs.helper_functions.parsers import zmq_uri_parser
from zmq_subs.helper_functions.signal_handler import SignalHandler


def main():
    """
    Process frame decoder block output

    Creates a ZeroMQ subscriber to connect to the coresponding ZeroMQ publisher
    to receive the output of the frame decoder block. After receiving each
    message they are processed and saved in JSON format in a file named with
    the datetime up to seconds resolution and if needed and extra counter for
    files created with the same timestamp. The subscriber is not blocking by
    using zmq.poll with a timeout of 500 ms.
    Positional arguments for the file prefix path and the ZeroMQ URI are
    parsed.
    The script is stopped if a SIGINT or a SIGTERM signal is received.
    The output json has the following fields:

    "decoder_corrected_bits": <int>,
    "decoder_crc_valid": <bool>,
    "decoder_name": <str>,
    "decoder_version": <str>(e.g "1.0"),
    "pdu": <str(ascii from base664)>,
    "sample_cnt": <int>,
    "sample_start": <int>,
    "time": <str iso8601 YYYY-MM-DDThh-mm-ss.ssssssZ>
    """
    prefix_path_args = prefix_path_parser().parse_known_args()[0]
    prefix_path = prefix_path_args.decoded_data_file_path
    zmq_uri_args = zmq_uri_parser().parse_known_args()[0]
    zmq_dump_host = zmq_uri_args.zmq_dump_host
    zmq_dump_port = zmq_uri_args.zmq_dump_port
    context, socket = open_sub_socket(zmq_dump_host, zmq_dump_port)
    print(f'ZMQ FRAME SUB Connecting to {zmq_dump_host}:{zmq_dump_port}')
    filename_array = []
    counter = 0

    signal_handler = SignalHandler()

    signal.signal(signal.SIGINT, signal_handler.handle)
    signal.signal(signal.SIGTERM, signal_handler.handle)

    while (not signal_handler.received_signal):
        if (socket.poll(500)):
            msg = socket.recv()
            pmt_blob = pmt.deserialize_str(msg)

            filename = "{}_{}".format(prefix_path, get_current_utc_time_str())
            if (filename in filename_array):
                filename += "_" + str(counter)
                counter += 1
            else:
                counter = 0
            filename_array.append(filename)
            metadata = pmt.to_python(pmt.car(pmt_blob))
            metadata["pdu"] = base64.b64encode(pmt.to_python(
                pmt.cdr(pmt_blob)).tobytes()).decode("utf-8")

            with open(filename, 'w+') as f:
                json.dump(metadata, f, sort_keys=True, indent=4)


if __name__ == "__main__":
    main()
