import threading

from flask import Flask, request, Response
from functions.APIFunctions import APIFunctions as api_function


def run_app_least_conn_1():
    app_least_conn_1 = create_app_least_conn_1()
    app_least_conn_1.run(host='0.0.0.0', port=8080)


def run_app_least_conn_2():
    app_least_conn_2 = create_app_least_conn_2()
    app_least_conn_2.run(host='0.0.0.0', port=9080)


def create_app_least_conn_1():
    app_least_conn_1 = Flask(__name__)

    @app_least_conn_1.route('/connections')
    # Check the number of connections which are in 'established' status
    def connections_handler_hold():
        port = request.environ.get('SERVER_PORT')
        count = api_function.get_established_connections_count(int(port))
        message = "I'm a #1 server(keep-connection-server)\nCurrent established connection count: {}\n".format(count)
        return Response(message, mimetype='text/plain')

    @app_least_conn_1.route('/inject-load')
    def inject_load_1():
        host = 'localhost'
        port = 8080
        duration = 120  # Keep connection for 2 mins

        # Using a thread feature, send requests to server
        thread = threading.Thread(target=api_function.establish_connection, args=(host, port, duration))
        thread.start()
        return Response("Injecting load... to a #1 server(keep-connection-server)\n", mimetype='text/plain')

    return app_least_conn_1


def create_app_least_conn_2():
    app_least_conn_2 = Flask(__name__)

    @app_least_conn_2.route('/connections')
    # Check the number of connections which are in 'established' status
    def connections_handler_release():
        port = request.environ.get('SERVER_PORT')
        count = api_function.get_established_connections_count(int(port))
        message = "I'm a #2 server(release-connection-server)\nCurrent established connection count: {}\n".format(count)
        return Response(message, mimetype='text/plain')

    @app_least_conn_2.route('/inject-load')
    def inject_load_2():
        host = 'localhost'
        port = 9080
        duration = 0  # Does not need to hold connections

        # Using a thread feature, send requests to server
        thread = threading.Thread(target=api_function.establish_connection, args=(host, port, duration))
        thread.daemon = True
        thread.start()
        return Response("Injecting load... to a #2 server(release-connection-server)\n", mimetype='text/plain')

    return app_least_conn_2
