import asyncio
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from database.db import Database
import uvicorn
from src.database.schemas import *
from src.auth.transport import Transport
from src.database.user import User

app = FastAPI(title='sclient-main-server')

### Settings
# TODO: Create .env

PORT = 7535
ADMIN_NAME = 'admin'
ADMIN_PASSWORD = 'admin'
DATABASE_USER = 'ADMIN'
DATABASE_PASS = '123123'
DATABASE_HOST = '127.0.0.1'
DATABASE_PORT = 5432
DATABASE_NAME = 'sonoma-db'
SECRET = 'SECRET'

###

db = Database(
        DATABASE_USER,
        DATABASE_PASS,
        DATABASE_HOST,
        DATABASE_PORT,
        DATABASE_NAME,
        SECRET
    )

transport = Transport(SECRET, db)

class App:
    def init(self, loop) -> None:
        config = uvicorn.Config(
            app,
            loop=loop,
            host='0.0.0.0',
            port=PORT
        )
        server = uvicorn.Server(config)
        loop.run_until_complete(server.serve())

    @app.get('/')
    async def docs(self: Request):
        return RedirectResponse(f'{self.url}docs')

    @app.get("/authenticated-route")
    async def authenticated_route(user: User = Depends(transport.current_active_user)):
        return {"message": f"Hello {user.email}!"}

def main():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    server = App()

    app.include_router(
        transport.fastapi_users.get_auth_router(transport.auth_backend), prefix="/auth/jwt", tags=["auth"]
    )
    app.include_router(
        transport.fastapi_users.get_register_router(UserRead, UserCreate),
        prefix="/auth",
        tags=["auth"],
    )
    app.include_router(
        transport.fastapi_users.get_reset_password_router(),
        prefix="/auth",
        tags=["auth"],
    )
    app.include_router(
        transport.fastapi_users.get_verify_router(UserRead),
        prefix="/auth",
        tags=["auth"],
    )
    app.include_router(
        transport.fastapi_users.get_users_router(UserRead, UserUpdate),
        prefix="/users",
        tags=["users"],
    )

    loop.run_until_complete(db.create_db_and_tables())
    server.init(loop)

if __name__ == '__main__':
    main()