#!/usr/bin/env python3

import os
import signal
import numpy as np
import soundfile as sf
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.signal_handler import SignalHandler


def main():
    """
    Process Audio stream

    Creates a ZeroMQ subscriber to connect to the coresponding ZeroMQ publisher
    to receive the audio stream and saves it as ogg format. 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.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 audio SUB Connecting to {zmq_dump_host}:{zmq_dump_port}')

    if os.path.exists(prefix_path):
        os.remove(prefix_path)

    outfile = sf.SoundFile(prefix_path, mode="w", samplerate=48000,
                           channels=1, format="OGG", subtype="VORBIS")
    signal_handler = SignalHandler()

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

    try:
        while (not signal_handler.received_signal):
            if (socket.poll(500)):
                msg = socket.recv()
                samples = np.frombuffer(msg, dtype=np.float32)
                outfile.write(samples)
    finally:
        outfile.close()
        socket.close()
        context.term()


if __name__ == "__main__":
    main()
