import socket
import time

import simpleaudio as sa

HOST = "0.0.0.0"
PORT = 9000

def save_file(client_socket):
    timestamp = str(int(time.time()))
    file_name = f"output_{timestamp}.wav"
    with open(file_name,'wb') as f:
        while True:
            l = client_socket.recv(1024)
            if not l: break
            f.write(l)
        
def play_file(conn):
    # you could consider sa.play_buffer ... I don't know if it would be more performant.
    try:
        play_obj = sa.play_buffer(conn.makefile(mode="rb").read(), 1,2,22050)
        play_obj.wait_done()
        #wave_object = sa.WaveObject.from_wave_file(conn.makefile(mode="rb"))
        #play_obj = wave_object.play()
        #play_obj.wait_done()
    except Exception as e:
        print(f"Hit an error: {e} skipping playback")
    return

# By default, socket.socket creates TCP sockets.
with socket.socket() as server_sock:
    # This tells the kernel to reuse sockets that are in `TIME_WAIT` state.
    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # This tells the socket what address to bind to.
    server_sock.bind((HOST, PORT))

    # 0 is the number of pending connections the socket may have before
    # new connections are refused.  Since this server is going to process
    # one connection at a time, we want to refuse any additional connections.
    server_sock.listen(0)
    print(f"Listening on {HOST}:{PORT}...")

    while True:
        # This is a blocking call as we wait for a new connection
        client_sock, client_addr = server_sock.accept()
        print(f"New connection from {client_addr}.")
        with client_sock as conn:
            play_file(conn)
