#!/home/nonroot/receive_motd_requests/venv/bin/python3
from flask import Flask
from flask import request
from flask_cors import CORS
from time import sleep
from settings import token, get_connection_ban_detector

app = Flask(__name__)
CORS(app)

@app.route('/', methods = ['POST'])
def get_answer():
    if request.remote_addr != "127.0.0.1":
        return "invalid"
    try:
        content = request.form.get('name')
        name = content.split(" ")[0]
        ip = content.split(" ")[1]
        #print(name, ip)
        if name is None or ip is None:
            return ""
    except:
        return ""
    name = name.replace('"', '') #fingerprint
    ip = ip.replace('"', '')
    with get_connection_ban_detector() as conn:
        with conn.cursor(buffered=True) as cur: #wtf is this buffered shit even
            sql_statement = """
                                UPDATE ban_detector.ban_detector x
                    SET fingerprint = %s,
                    modified_on = now()
                WHERE
                        x.ip = %s
                    and
                        x.last_connect = (select last_connect
                                    from ban_detector.ban_detector x1
                                    where
                                        x1.ip = %s
                                    order by last_connect desc limit 1);
                """
            cur.execute(sql_statement, [name, ip, ip])
            conn.commit()
    conn.close()
    print("comitting content: ", content)
    return ""


if __name__ == "__main__":
    from waitress import serve
    serve(app, host="localhost", port=5085, threads = 8)

