# cPy - microdot http and websocket server
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-02-22  Initial release

import  json
from	microdot			import	Microdot, send_file
from	microdot.websocket	import	with_websocket

# Implemented:
# microdotSetup (tg, parent)
# |parent.doCommand(obj)
# ~wsSend(d)

# ============= module global variables ===================

class G:
    app 	  = Microdot()
    websocket = None
    parent	  = None


def microdotSetup (tg, parent):
    G.parent = parent
    tg.create_task(G.app.start_server(debug=True))

# ==================== HTTP server ========================

# serve home page file
@G.app.route('/')
async def index(request):
    return send_file('static/index.html')


# serve other static files
@G.app.route('static/<path:path>')
async def static(request, path):
    if '..' in path:
        return 'Not found', 404		# directory traversal not allowed
    return send_file(f'static/{path}')

# =================== Websocket server =====================

# handle created websockets and incoming data
@G.app.route('/ws')
@with_websocket
async def onWs(request, ws):
    if G.websocket: return                          # accept only one ws connection
    G.websocket = ws  			                	# add to active websockets
    try:
        while True:
            obj = json.loads(await ws.receive())
            if res := G.parent.doCommand(obj):
                await wsSend(res)
    except : print('webServer.onWs: exception')
    finally: G.websocket = None


# send dictionary d to connected websocket
async def wsSend(d):
    if isinstance(d, dict):
        s = json.dumps(d)
        await G.websocket.send(s)
    else: print('wsSend no dict object')

# ========================== end ===============================
