from piccolo_admin.endpoints import create_admin
from piccolo.engine import engine_finder
from starlette.routing import Route, Mount
from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles

from home.endpoints import HomeEndpoint
from home.piccolo_app import APP_CONFIG


app = Starlette(
    routes=[
        Route("/", HomeEndpoint),
        Mount("/admin/", create_admin(tables=APP_CONFIG.table_classes)),
        Mount("/static/", StaticFiles(directory="static")),
    ],
)

{% if engine == 'postgres' %}
@app.on_event("startup")
async def open_database_connection_pool():
    engine = engine_finder()
    await engine.start_connnection_pool()


@app.on_event("shutdown")
async def close_database_connection_pool():
    engine = engine_finder()
    await engine.close_connnection_pool()
{% endif %}

if __name__ == "__main__":
    {% if server == 'uvicorn' %}
    import uvicorn

    uvicorn.run(app)
    {% elif server == 'Hypercorn' %}
    from hypercorn.asyncio import serve

    serve(app)
    {% endif %}
