import os, sys

from starlette.applications import Starlette
from starlette.responses import HTMLResponse, JSONResponse, Response
from starlette.routing import Route

if "peers_identity" not in sys.path:
    sys.path.insert(0, os.path.abspath("."))

from peers_identity import register, inbox, outbox


async def get_request_json(request):
    try:
        return await request.json()
    except:
        return None


async def homepage_r(request):
    return Response("Welcome home.", media_type="text/plain")


async def register_r(request):
    return JSONResponse(register(await get_request_json(request)))


async def inbox_r(request):
    return JSONResponse(inbox())


async def outbox_r(request):
    return JSONResponse(outbox())


app = Starlette(
    debug=True,
    routes=[
        Route("/", homepage_r),
        Route("/register", register_r, methods=["POST"]),
        Route("/inbox", inbox_r, methods=["POST"]),
        Route("/outbox", outbox_r, methods=["POST"]),
    ],
)
