# server.py
from flask import Flask, render_template
from flask_socketio import SocketIO
import numpy as np
import json

app = Flask(__name__)

socketio = SocketIO(app,
                    async_mode='threading',
                    )


# Function to generate a random NumPy matrix
def generate_matrix():
    return np.random.rand(3, 3)

# Function to send the matrix to the client
def send_matrix():
    matrix = generate_matrix()
    matrix_json = json.dumps(matrix.tolist())
    socketio.emit('matrix', matrix_json)

# Background thread to send the matrix every 5 seconds
def background_thread():
    while True:
        send_matrix()
        socketio.sleep(5)

    
# Route for the HTML page
@app.route('/')
def index():
    return render_template('index.html')

# Socket.IO event handlers
@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

@socketio.on('message')
def handle_message(message):
    print('Received message:', message)

if __name__ == '__main__':

    socketio.start_background_task(target=background_thread)
    
    socketio.run(app, host="0.0.0.0", port=5002)
