#!/usr/bin/env python3
import signal
from zmq_subs.helper_functions.zmq_create_context import open_sub_socket
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.date_helpers import get_current_utc_time_str
from zmq_subs.helper_functions.signal_handler import SignalHandler


def main():
    """
    Process IQ stream

    Creates a ZeroMQ subscriber to connect to the coresponding ZeroMQ publisher
    to receive the IQ stream and saves it as raw format in a file named with
    the datetime up to seconds resolution. 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.

    """
    prefix_path_args = prefix_path_parser().parse_known_args()[0]
    prefix_path = prefix_path_args.iq_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 IQ SUB Connecting to {zmq_dump_host}:{zmq_dump_port}')
    # TODO: Add sampling rate to the filename
    filename = f"{prefix_path}_cs16_{get_current_utc_time_str()}.raw"

    signal_handler = SignalHandler()

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

    with open(filename, "wb") as f:
        while (not signal_handler.received_signal):
            if (socket.poll(500)):
                msg = socket.recv()
                f.write(msg)
    socket.close()
    context.term()


if __name__ == "__main__":
    main()
