# *Py - aio microdot webserver serving current time with refresh
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2025-11-26  initial release

import	asyncio
import	time
from	microdot	import	Microdot, Response

# ===================== local ===========================

html = '''
<h2>Time server</h2>
The current time = 00:00:00<br>
Enjoy the rest of your day
<script>
    function onTimer() {location.reload()}
    setInterval(onTimer, 1000)
</script>'''

def updatedHtml():
    now   = time.localtime()
    now_s = time.strftime('%H:%M:%S', now)
    idx   = html.index('00:00:00')
    return f'{html[:idx]}{now_s}{html[idx+8:]}' 
    
# ==================== webserver ========================

app  						  = Microdot()
Response.default_content_type = 'text/html'

@app.route('/')
async def index(request):
    return updatedHtml()


@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}')

# ======================= main ==========================

# Three cooperative asyncio tasks
#    task #1: webserver
#    task #2: print '*' @ 1 Hz
async def main():
    asyncio.create_task(app.start_server(debug=True))	# task #1
    while True:											# task #2
        await asyncio.sleep(1)
        print('*', end='')


asyncio.run(main())
    
# ======================== end ===========================
