import asyncio
import logging

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

from src.db_engine import create_engine
from src.config import settings
from src.main_tasks import start_tasks, shutdown_tasks

logger = logging.getLogger(__name__)


async def homepage(request):
    async with app.state.engine.acquire() as conn:
        rows = await conn.execute('SELECT 1')
        result = []
        async for row in rows:
            result.append(row[0])

        return JSONResponse({'result': result})


async def on_startup_task():
    logger.info('Web app starting...')
    if settings.ENV_TYPE in ('development', ):
        await asyncio.sleep(2.0)  # wait for postgres container start

    app.state.engine = await create_engine()
    await start_tasks(app)
    logger.info('Web app started')


async def on_shutdown_task():
    await shutdown_tasks(app)

app = Starlette(
    debug=True,
    routes=[Route('/', homepage)],
    on_startup=[on_startup_task],
    on_shutdown=[on_shutdown_task],
)
