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

app = Flask(__name__)

socketio = SocketIO(app,
                    #async_mode='threading',
                    #transorts=['websocket'],
                    binary=True,
                    )


# Function to send the matrix to the client
def send_dm():
    es = requests.get("http://sharknirws.shark-nir.lbto.org:5001/api/rtc/plots/")
    #es = {"dm":"ciccio"}

    if "dm" in es.json():
        shape = np.array(es.json()["dm"]["shape"])
        flat = np.array(es.json()["dm"]["flat"])
        matrix = shape-flat
        print(matrix)
        #print((Time.now()-now).sec, "fetched")                                     
    
        binary_data = np.array(matrix).astype("float32").tobytes()
        socketio.emit(u'matrix', {u'data': binary_data})


def send_matrix():
    # shape = (30, 20)
    # matrix = np.random.uniform(-65535, 65535, shape).astype("float32")
    # binary_data = matrix.tobytes().decode("ISO-8859-1")
    # print(matrix)
    # print(len(binary_data))
    # print(len(matrix.tolist()))

    binary_data = np.array([[0, 1.1], [2.2, 3.3]]).astype("float32").tobytes()
    socketio.emit(u'matrix', {u'data': binary_data})
    
# Background thread to send the matrix every 5 seconds
def background_thread():
    while True:
        socketio.sleep(2)
        send_matrix()


# 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)
