import resource
from matplotlib import pyplot as plt
from modules import cosmic
from modules import tidi
from modules import saber
from modules import radar
from modules import balloon
from quart import Quart, request
from quart_cors import cors
from typing import get_args
import sys
import matplotlib.font_manager as fm

app = Quart(__name__)
app = cors(app, send_origin_wildcard=True, allow_origin="*")

# limit the whole app not to use over 8G ram
# use resource module to do this
# resource.setrlimit(resource.RLIMIT_AS, (8 * 1024 * 1024 * 1024, -1))

plt.switch_backend('agg')
fm.fontManager.addfont("./SimHei.ttf")


@app.before_request
def auth():
    # check for method
    # if it is OPTIONS, do not check for auth
    if request.method == "OPTIONS":
        return
    code = request.headers.get("Authorization")
    print(code)
    if code != "0101":
        return "Unauthorized", 401


@app.route("/ping")
def ping():
    return "pong"


app.register_blueprint(balloon.balloon_module, url_prefix="/balloon")
app.register_blueprint(radar.radar_module, url_prefix="/radar")
app.register_blueprint(saber.saber_module, url_prefix="/saber")
app.register_blueprint(tidi.tidi_module, url_prefix="/tidi")
app.register_blueprint(cosmic.cosmic_module, url_prefix="/cosmic")
# allow cors


if __name__ == '__main__':
    # get args '--prod'
    args = sys.argv
    if 'prod' in args:
        app.run("0.0.0.0", port=5000, debug=False)
        pass
    elif 'debug' in args:
        app.run("0.0.0.0", port=18200, debug=True)
    else:
        raise Exception("Invalied Mode")
