import sys
import os
sys.path.insert(0, os.path.abspath('../'))

import socket

import numpy as np
import scipy.io.wavfile as wavfile

from AmmosAudioSocketReader import AmmosAudioSocketReader


if __name__ == '__main__':
    frames = []

    # create socket
    in_socket = socket.socket()
    in_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    in_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    in_socket.bind(('127.0.0.1', 12345))
    print('Waiting for connection')
    in_socket.listen(1)
    conn, _ = in_socket.accept()
    print('Connected')

    # create AmmosAudioSocketReader
    socket_reader = AmmosAudioSocketReader(conn)

    print('Reading Frames')
    while True:
        try:
            frames.append(socket_reader.read_next_frame())
        except KeyboardInterrupt:
            break

    # write frames to wav file
    print('Writing frames to Wav File')
    audio = np.concatenate([frame[0] for frame in frames])
    print(audio)
    wavfile.write(f"test.wav", frames[0][1], audio)