import threading

from flask import Flask
from flask_redis import Redis
from redis import StrictRedis

from event_logger import EventLogger

# TOGGLE if every received message shall be redirected to redis
LOG_TO_REDIS = True
# TOGGLE if every received message shall be printed to console
VERBOSE = True

# make sure redis (container) is running and accessible

# see https://flask-and-redis.readthedocs.io/en/latest/
# see https://github.com/andymccurdy/redis-py

app = Flask(__name__)
app.config["REDIS_HOST"] = "redis"
app.config["REDIS_PORT"] = 6379
redis: StrictRedis = Redis(app)


@app.route("/")
def get_keys():
    keys = redis.keys()
    keys.sort()
    return 'Existing keys:<br><br>{}'.format(
        ['<a href="/api/keys/{0}/">{0}</a>'.format(key.decode()) for key in keys]) + \
           'DAF: DatenaufzeichnungAutonomesFahren, TL: TrafficLight, TV: TargetVelocity' \
           '<br><br>' \
           '<br><br>Access Api via <br><br>' \
           'GET /api/keys<br>' \
           'GET /api/keys/&lt;key&gt;<br>'


@app.route("/api/keys")
def api_get_keys():
    """
    :return: list of available redis keys
    """
    return el.get_keys()


@app.route("/api/keys/<key>/")
def api_get_of_key(key):
    """
    :param key: key to get data of
    :return: list of data to the respective key
    """
    return el.get_list_of(key)


@app.route("/api/keys/<key>/<index>/")
def api_get_index_of_key(key, index):
    """
    :param key: key to get data element of
    :param index: index of keys data list
    :return: element matching index of key
    """
    return el.get_index_of(key, index)


if __name__ == '__main__':
    el = EventLogger(redis, LOG_TO_REDIS, VERBOSE)
    threading.Thread(target=el.setup_msq_queue).start()
    threading.Thread(target=app.run, args=('0.0.0.0', 5001)).start()
