import threading
from typing import Any, Callable
from wsgiref.simple_server import make_server

import port_for
from flask import Flask, abort, request


class TriggerServerThread(threading.Thread):
    """Simple Flask server (wrapped as thread) for triggering actions on sesssions."""

    def __init__(self, trigger_method: Callable[[str], Any]):
        super().__init__()
        self.port = port_for.select_random()

        app = Flask(__name__)

        @app.route("/", methods=["POST"])
        def trigger():
            json = request.json
            token = json.get("token", "")
            r = trigger_method(token)
            if r:
                return "Successful triggered"
            else:
                return abort(403)

        self.srv = make_server("127.0.0.1", self.port, app)
        self.ctx = app.app_context()
        self.ctx.push()

    def run(self):
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()
