from flask import Flask, jsonify
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import serial
import serial.tools.list_ports
import threading
import time

app = Flask(__name__)

CORS(app, origins=["http://localhost:5173", "https://station-stg.qatrace.com"], supports_credentials=True)
socketio = SocketIO(app, cors_allowed_origins="https://station-stg.qatrace.com")

# Dictionary to track active threads for each port
active_threads = {}

# Function to listen to a selected serial port and emit data over WebSocket
def listen_to_scale(port, baud_rate=9600):
    try:
        with serial.Serial(port, baud_rate, timeout=1) as ser:
            while True:
                if ser.in_waiting > 0:
                    raw_data = ser.readline().decode('utf-8').strip()
                    socketio.emit('scale_data', {'weight': raw_data})  # Emit data to frontend
    except Exception as e:
        socketio.emit('error', {'error': str(e)})

# WebSocket event to start listening to a selected port
@socketio.on('start_listening')
def handle_start_listening(data):
    global active_threads
    
    # Get the new port
    new_port = 'COM1'
    if new_port:
        # If there's already a thread listening, stop it
        if new_port in active_threads:
            socketio.emit('error', {'error': f'Already listening to {new_port}'})
            return

        # Check if we were listening to another port and stop it
        for port, thread in list(active_threads.items()):
            if thread.is_alive():
                # Stop the thread for the previous port
                thread._stop()  # Forcefully stop the old thread
                socketio.emit('error', {'error': f'Stopped listening to {port}'})
                break

        # Start a new thread to listen to the selected port
        thread = threading.Thread(target=listen_to_scale, args=(new_port,))
        active_threads[new_port] = thread
        thread.start()

        socketio.emit('info', {'message': f'Started listening to {new_port}'})

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5002, debug=False)
