from flask import Flask, request, jsonify
import mysql.connector
from queries import *
app = Flask(__name__)

@app.route('/')
def index():
    node = request.args.get('node', default = None)
    dataType = request.args.get('dataType', default = None)
    MAC = request.args.get('MAC', default = None)
    return getData(node, dataType, MAC)

@app.route('/updateData')
def updateDataIndex():
    node_id = request.args.get('node', None)
    new_name = request.args.get('name', None)
    new_location = request.args.get('location', None)
    return updateData(node_id, new_name, new_location)

@app.route('/getNodeInfo')
def getNodeInfoIndex():
    macAdress = request.args.get('macAdress', None)
    return getNodeInfo(macAdress)

def updateData(node, name, location):
        mydb = loginDB()
        query = update_query(node, name, location)
        cursor = mydb.cursor(dictionary=True)  # Enable dictionary output
        cursor.execute(query)
        mydb.commit()
        result = cursor.fetchall()  # Fetch the results
        cursor.close()
        mydb.close()

        return result

def loginDB():
        mydb = mysql.connector.connect(
            host="localhost",
            user="root",
            password="Dingleberries69!",
            database="NodeData"
        )
        return mydb

def getData(node, dataType, MAC):
        mydb = loginDB()
        query = get_query(node, dataType, MAC)
        cursor = mydb.cursor(dictionary=True)  # Enable dictionary output
        cursor.execute(query)
        result = cursor.fetchall()  # Fetch the results
        cursor.close()
        mydb.close()

        return result

def getNodeInfo(macAdress):
        mydb = loginDB()
        query = get_query(False, False, macAdress)
        cursor = mydb.cursor(dictionary=True)  # Enable dictionary output
        cursor.execute(query)
        result = cursor.fetchall()  # Fetch the results
        cursor.close()
        mydb.close()

        return result

if __name__ == '__main__':
    app.run(debug=True, host='localhost')
