import asyncio
import websockets
import mysql.connector
import json

async def process_data(data):
    try:
        mydb = mysql.connector.connect(
            host="localhost",
            user="root",
            password="Dingleberries69!",
            database="NodeData" 
        )
        cursor = mydb.cursor()

        MACDataReading = mydb.cursor()
        MACDataReading.execute("SELECT MAC FROM Node")
        print('some_response')
        query = "INSERT INTO `Measurement` (NodeID, Type, Value) VALUES (%s, %s, %s)"
        processedData = json.loads(data)
        processedTemp = (processedData['Temp'])
        processedHumi = (processedData['Humi'])
        processedeCO2 = (processedData['eCO2'])
        processedTvoc = (processedData['TVOC'])
        processedMAC = (processedData['node'])
        MACTuple = (processedMAC,)

        MACDataFetching = MACDataReading.fetchall()
        MACArray = list(MACDataFetching)
        

        if MACTuple not in MACArray:
          addingNode = "INSERT INTO `Node` (MAC) VALUES (%s)"
          cursor.execute(addingNode, MACTuple)
          mydb.commit()

        pushingDataArray = [(1, "Temp", processedTemp), (1, "Humi", processedHumi), (1, "eCO2", processedeCO2), (1, "TVOC", processedTvoc)]
        for i in pushingDataArray:
            print(query ,i)
            cursor.execute(query, i)
            mydb.commit()
        
    except mysql.connector.Error as err:
        print("MySQL Error:", err)
    finally:
        cursor.close()
        mydb.close()

async def receive_data():
    uri = "ws://145.92.8.114/ws"

    try:
        async with websockets.connect(uri) as websocket:
            while True:
                data = await websocket.recv()
                print(f"Received data: {data}")
                await process_data(data)
    except websockets.ConnectionClosedError as e:
        print("WebSocket connection closed:", e)

async def main():
    await receive_data()

asyncio.run(main())
    
