from typing import AnyStr

from fastapi import APIRouter, Request
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.templating import Jinja2Templates
from sqlalchemy import or_

from src.core.security import get_current_user_from_token
from src.db.models.admin import Profile
from src.db.models.media import MediaFile
from src.core.log_conf import logger
from src.db.session import SessionDep

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

@router.get("/files")
def get_mediafiles(db: SessionDep, request: Request, msg: str | None = None):
    params = request.query_params
    query = params.get("query")
    filter = {}
    review = params.get('review') == "on"
    if review:
        filter['review'] = True
    download = params.get("download") == "on"
    if download:
        filter['should_download'] = True
    if query is not None and len(query) > 0:
        filter['url'] = query
    if len(filter) > 0:
        if "url" in filter:
            mediafiles  = db.query(MediaFile).filter(or_(MediaFile.title.ilike(f'%{query}%'), MediaFile.url.ilike(f"%{query}%")))
        else:
            mediafiles = db.query(MediaFile).filter_by(**filter).all()
    else:
        mediafiles = db.query(MediaFile).all()
    try:
        token = request.cookies.get("access_token")
        scheme, 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)
        return templates.TemplateResponse("media/files.html", {"request": request, "msg": msg, "mediafiles": mediafiles})
    except Exception as e:
        print(e)
        logger.info("User is not authorized, no data shown")
        msg = "Nicht berechtigt!!"
        return templates.TemplateResponse("media/files.html", {"request": request, "msg": msg, "mediafiles": []})

@router.get("/files/{file_id}")
def file_details(file_id: AnyStr, request: Request, db: SessionDep):
    mediafile = db.get(MediaFile, file_id)
    return templates.TemplateResponse("media/file_detail.html", {"request": request, "mediafile":mediafile})

@router.get("files/edit/{file_id}")
def edit_file(db: SessionDep, request: Request, file_id: str):
    media_file = db.get(MediaFile, file_id)
    return templates.TemplateResponse("media/file_detail.html", {"request": request, "mediafile":media_file})
