import os
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
import ping

app = Quart(__name__, static_folder="./res")
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")

with open("./passcode.txt", "r") as f:
    code = f.read()
    if code:
        code = code.strip()
    else:
        code = "0101"


@app.before_request
def auth():
    # check for method
    # if it is OPTIONS, do not check for auth
    if request.method == "OPTIONS" or not request.path.startswith("/api"):
        return
    if request.path.startswith("/api/ping"):
        return
    _code = request.headers.get("Authorization")
    if _code != code:
        return "Unauthorized", 401


@app.route('/')
async def return_index_html():
    return await app.send_static_file("index.html")


@app.route("/<path:path>")
async def index(path):
    # check if there is path in static folder
    # if not, return index.html
    if app.static_folder:
        # check if the file exists
        if os.path.exists(os.path.join(app.static_folder, path)):
            #
            return await app.send_static_file(path)
    return await app.send_static_file("index.html")

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


if __name__ == '__main__':
    # get args '--prod'
    args = sys.argv
    print(os.getcwd())
    # read from ENV Z_PORT
    env_port = os.getenv("Z_PORT")
    port = 5000 if env_port is None else int(env_port)
    if 'debug' in args:
        app.run("0.0.0.0", port=58620, debug=True)
    else:
        app.run("0.0.0.0", port=port, debug=False)
