import serial
import json
import os
import asyncio
import websockets
import time

from dotenv import load_dotenv

load_dotenv()

server_ws = os.getenv('SERVER_WS')

arduino_port = os.getenv('ARDUINO_PORT')
timeout = eval(os.getenv('TIMEOUT'))
baudrate = eval(os.getenv('BAUDRATE'))

ser = serial.Serial(arduino_port, baudrate, timeout=timeout)

temps_recuperation_distance = eval(os.getenv('TEMPS_RECUPERATION_DISTANCE'))


async def process_distance(distance, websocket, counter):
    payload = {'distance': distance}
    if counter == temps_recuperation_distance:
        await websocket.send(json.dumps(distance))
        counter = 0
    else:
        counter += 1

    return counter


async def process_notification(message):
    print(f"Notification reçue : {message}")

    notification_methode = message
    print(f"Nouvelle méthode de notification reçue: {notification_methode}")
    ser.write(bytes(notification_methode, 'utf-8'))


async def read_serial(websocket):
    counter = temps_recuperation_distance
    while True:
        line = ser.readline().decode('utf-8').rstrip()
        print(f"Line : {line}")

        if 'Distance' in line:
            distance = float(line.split(':')[-1].strip().split(' ')[0])
            print(f"Distance : {distance} cm")
            counter = await process_distance(distance, websocket, counter)

        await asyncio.sleep(0.1)


async def message_recu(websocket):
    while True:
        # Attendre un message du serveur WebSocket
        message = await websocket.recv()

        # Traitement du message reçu
        await process_notification(message)


async def main():
    async with websockets.connect(server_ws) as websocket:
        try:
            print("Connexion au serveur WebSocket établie.")

            # Utilisation de asyncio.create_task pour démarrer les coroutines en parallèle
            task1 = asyncio.create_task(message_recu(websocket))
            task2 = asyncio.create_task(read_serial(websocket))

            # Attendre que les deux tâches soient terminées
            await asyncio.gather(task1, task2)

        except KeyboardInterrupt:
            ser.close()
            print("Arrêt du programme.")


if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())
