from fastapi import Cookie, Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from sqlalchemy.orm import Session
from dotenv import load_dotenv
from threading import Thread
from asyncio import run
import os

from db import database, models, crud
from db.database import get_db
from routers import *
from video_capture import handle_cameras

app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

# load environment variables
load_dotenv()

origins = [
    os.getenv('WEB_ROOT'),
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)


@app.on_event("startup")
async def on_startup():
    # Database creation
    models.Base.metadata.create_all(bind=database.engine)
    t = Thread(target=run, args=(handle_cameras(),))
    t.start()


# Docs OpenAPI
@app.get("/api/openapi.json")
async def get_open_api_endpoint(connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    if user.admin:
        return JSONResponse(get_openapi(title="FastAPI", version=1, routes=app.routes))


@app.get("/api/docs")
async def get_documentation(connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    if user.admin:
        return get_swagger_ui_html(openapi_url="/api/openapi.json", title="docs")


# Integration of routers
app.include_router(infos.router)
app.include_router(records.router)
app.include_router(stats.router)
app.include_router(news.router)
app.include_router(comments.router)
app.include_router(authentication.router)
app.include_router(websocket.router)
