#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""API server, with a web client for free"""

# System modules
import time

# Third-party modules
from flask import Flask, request
from flask_cors import CORS

# Custom modules
from api import api_blueprint as api
from web.server import instance

app = Flask(__name__)
app.register_blueprint(api, url_prefix='/api')
app.threaded = True

cors = CORS(app)

@app.route('/all/<string:namespace>')
def get_status(namespace):
    '''Build a global status for a given namespace'''
    wait = float(request.args.get('wait', 0))
    endpoints = {}

    # Check for ping before going to all others
    power = f"/api/{namespace}/ping"
    with app.test_client() as client:
        res = client.get(power)
        name = "-".join(power.split("/")[2:]) # "dome-shutter-movement"
        endpoints[name] = res.get_json()
        if not res.get_json()["response"]:            
            return endpoints
    
    for rule in app.url_map.iter_rules():
        if rule.rule.startswith(f"/api/{namespace}/"): # "/api/dome/shutter/movement"
            if "GET" in rule.methods:
                with app.test_client() as client:
                    res = client.get(rule.rule)
                    name = "-".join(rule.rule.split("/")[2:]) # "dome-shutter-movement"
                    endpoints[name] = res.get_json()
                    time.sleep(wait)

    return endpoints

if __name__ == "__main__":

    # System modules
    import sys

    with_web = True
    try:
        arg = sys.argv[1]
        if arg.startswith("--noweb"):
            with_web = False
            port = 5533
        else:
            port = arg
    except IndexError as e:
        port = 5533

    hostname = "0.0.0.0"

    print(f"hostname {hostname}")

    if with_web:
        socketio = instance.enable(app)
        socketio.run(app, host=hostname, port=port)
    else:
        app.run(host=hostname, port=port)
