import flask
import json
from flask import request, jsonify

from database import db_management as mldb
from machinelearning import ml as ml

app = flask.Flask(__name__)
app.config["DEBUG"] = True

def prepare_return_data(result):
    result = json.dumps({'result': result})
    print(result)
    return result

@app.route('/getall')
def getall():
    jobs = mldb.get_all()

    results = [tuple(row) for row in jobs]
    return prepare_return_data(results)

@app.route('/get')
def get():
    request_data = request.get_json()
    JobId = int(request_data['JobId'])
    job = tuple(mldb.get_job(JobId))

    return prepare_return_data(job)

@app.route('/add', methods=['POST'])
def add():
    request_data = request.get_json()

    RunId = request_data['RunId']
    AUC = float(request_data['AUC'])
    Accuracy = float(request_data['Accuracy'])
    Arguments = request_data['Arguments']
    TrainingContext = request_data['TrainingContext']
    RunStatus = int(request_data['RunStatus'])

    id = mldb.add_job(RunId, AUC, Accuracy, Arguments, TrainingContext, RunStatus)

    return prepare_return_data(id)


@app.route('/update', methods=['PUT'])
def update():
    request_data = request.get_json()
    JobId = int(request_data['JobId'])
    RunId = request_data['RunId']
    AUC = float(request_data['AUC'])
    Accuracy = float(request_data['Accuracy'])
    Arguments = request_data['Arguments']
    TrainingContext = request_data['TrainingContext']
    RunStatus = int(request_data['RunStatus'])

    job = mldb.update_job(JobId, RunId, AUC, Accuracy, Arguments, TrainingContext, RunStatus)
    job = tuple(job)

    return prepare_return_data(job)


@app.route('/run', methods=['POST'])
def run_exp():
    request_data = request.get_json()
    p1 = float(request_data['p1'])
    p2 = float(request_data['p2'])
    p3 = float(request_data['p3'])
    p4 = float(request_data['p4'])

    id = ml.create_run_experiment(p1, p2, p3, p4)
    return prepare_return_data(id)

# @app.route('/calculate', methods=['POST'])
# def calculate():
#     data = request.get_json()

#     # Retrieve the required input fields from the data
#     run_id = data.get('RunId')
#     auc = data.get('AUC')
#     accuracy = data.get('Accuracy')
#     arguments = data.get('Arguments')
#     training_context = data.get('TrainingContext')
#     run_status = data.get('RunStatus')

#     # Perform the necessary calculations
#     result = auc * accuracy

#     # Store the calculated result in the database
#     job_id = mldb.add_job(run_id, auc, accuracy, arguments, training_context, run_status, result)

#     # Prepare the response
#     response = {
#         'JobId': job_id,
#         'Result': result
#     }

#     return jsonify(response)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8002)
