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

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

# System modules
import configparser
import logging
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)

# Load the config file
ends = configparser.ConfigParser()
ends.read('./config/api.ini')

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

    # List of get-priorities, if any.
    for section in ends.sections():
        if section.startswith("/"+namespace):
            priority = ends[section].getint('get-priority', float('inf'))
            sections.append((priority, section))
    # Sorting by priority
    sections.sort()

    # GET starting from prioritized. If prioritized fails, break.
    for pri, sec in sections:
        time.sleep(wait)
        with app.test_client() as client:

            cli = client.get(f"/api{sec}")
            if cli.status_code != 405:  # 405 Method Not Allowed
                
                res = cli.get_json()
                name = "-".join(sec.split("/")[1:]) # "telescope-power"
                endpoints[name] = res

                if pri != float('inf'):
                    if "raw" in res:
                        if not res["raw"]:
                            break
                    elif "response" in res: # just for telesope/clock
                        if (res["response"] == "FAILED 2"):
                            break

    return endpoints

# @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-ping"
#         endpoints[name] = res.get_json()
#         if "raw" in res.get_json():
#             if not res.get_json()["raw"]:            
#                 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)
