import sys
import os
from aiohttp import web

from proxy import proxy_ws, proxy_http

[_, host, port, file_root, ws_proxy_url] = sys.argv

def print_usage():
    print("""Usage: python3 ./backend.py <host> <port> <file_root> <ws_proxy_url>""")


async def handle_service(request: web.Request):
    [service, medium, target] = [
        request.match_info.get('service'),
        request.match_info.get('medium'),
        request.match_info.get('target')
    ]

    if 'vnc' in request.url.path:
        print("caught vnc request")
        return await proxy_http(request)

    if not service or not medium:
        return web.json_response({"success": "false", "message": "Missing Serice or Medium"})

    if not target:
        target = "index.html"

    serve_path = f"{file_root}/service/{service}/{medium}/{target}"
    print(f"looking for path {serve_path}")

    if not os.path.exists(serve_path):
        data = { "success": "false", "message": "Not Found" }
        return web.json_response(
            status=404,
            data=data,
        )
    return web.FileResponse(serve_path)


async def serve_http(request: web.Request):
    path_info = request.match_info.get('path_info', '')

    print(f"Req: {request} with path: {path_info}")

    if '..' in path_info:
        data = {"success": "false", "message": "Forbidden"}
        return web.json_response(
            status=403,
            data=data,
            content_type='application/json'
        )
    elif path_info == '':
        path_info = "index.html"

    serve_path = f"{file_root}/{path_info}"

    print(f"looking for path {serve_path}")

    if not os.path.exists(serve_path):
        data = { "success": "false", "message": "Not Found" }
        return web.json_response(
            status=404,
            data=data,
        )
    return web.FileResponse(serve_path)

def build_http_server():
    app = web.Application()
    app.add_routes([
        web.get('/{service}/{medium}/{target:.*}', handle_service),
        web.get("/{service}/websockify", proxy_ws),
        web.get("/{path_info:.*}", serve_http),
    ])

    return app

def main(host, port):
    app = build_http_server()
    web.run_app(app, host=host, port=int(port))

try:
    main(host, port)

except ValueError as e:
    print(f"Argv Error: {e}")
    print_usage()

except Exception as e:
    print("Caught exception: {e}")
    print_usage()
