from fastapi import APIRouter, Request, status, responses
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.templating import Jinja2Templates

from src.core.security import get_current_user_from_token
from src.db.models.media import MediaVideo
from src.db.models.admin import Profile
from src.db.repository.media.video import create_new_video
from src.db.session import SessionDep
from src.webapps.media.forms import AddLinkForm

templates = Jinja2Templates(directory="src/templates")
router = APIRouter(include_in_schema=False, prefix="/media")

@router.get("/videos")
def get_mediavideos(db: SessionDep, request: Request, msg: str = None):
    mediavideos = db.query(MediaVideo).all()
    try:
        token = request.cookies.get("access_token")
        _, param = get_authorization_scheme_param(token)  # scheme will hold "Bearer" and param will hold actual token value
        current_user: Profile = get_current_user_from_token(token=param, db=db)
        return templates.TemplateResponse("media/videos.html", {"request": request, "msg": msg, "user": current_user, "mediavideos": mediavideos})
    except Exception as e:
        print(e)
    return templates.TemplateResponse("media/videos.html", {"request": request, "msg": msg, "user": None, "mediavideos": mediavideos})

@router.get("/videos/{video_id}")
def video_details(video_id: str, request: Request, db: SessionDep):
    mediavideo = db.get(MediaVideo, video_id)
    return templates.TemplateResponse("media/video_detail.html", {"request": request, "mediavideo":mediavideo})

@router.get("/add-link")
def add_video_link(request: Request, db: SessionDep):
    return templates.TemplateResponse("media/add_video_link.html", {"request": request})

@router.post("/add-link")
async def post_video_link(request: Request, db: SessionDep):
    form = AddLinkForm(request)
    await form.load_data()
    if form.is_valid():
        try:
            #video = AddLink(**form.__dict__)
            mediavideo = create_new_video(video=form, db=db)
            return responses.RedirectResponse(f"media/videos/{mediavideo.id}", status_code=status.HTTP_302_FOUND)
        except Exception as e:
            print(e)
            form.__dict__.get("errors").append("Link already added")
            return templates.TemplateResponse("media/add_video_link.html", form.__dict__)
    return templates.TemplateResponse("media/add_video_link.html", form.__dict__)

