import os
from fastapi import APIRouter, HTTPException, Depends
from starlette.responses import FileResponse
from sqlalchemy.orm import Session

from app.model.crud.project_image_crud import get_img_url
from app.model.crud.project_detect_crud import get_detect_img_url, get_log_img_url
from app.config.config_reader import images_url
from app.db.db_session import get_db

view = APIRouter()


@view.get("/view_img/{image_id}")
def view_img(image_id: int, session: Session = Depends(get_db)):
    """
    查看图片
    :param session:
    :param image_id: 图片id
    :return:
    """
    sour_url, thumb_url = get_img_url(image_id, session)
    image_path = os.path.join(images_url, sour_url)
    # 检查文件是否存在以及是否是文件
    if not os.path.isfile(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path, media_type='image/jpeg')


@view.get("/view_thumb/{image_id}")
def view_thumb(image_id: int, session: Session = Depends(get_db)):
    """
    查看图片
    :param session:
    :param image_id: 图片id
    :return:
    """
    sour_url, thumb_url = get_img_url(image_id, session)
    image_path = os.path.join(images_url, thumb_url)
    # 检查文件是否存在以及是否是文件
    if not os.path.isfile(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path, media_type='image/jpeg')


@view.get("/view_detect_img/{image_id}")
def view_detect_img(image_id: int, session: Session = Depends(get_db)):
    """
    查看图片
    :param session:
    :param image_id: 图片id
    :return:
    """
    sour_url, thumb_url = get_detect_img_url(image_id, session)
    image_path = os.path.join(images_url, sour_url)
    # 检查文件是否存在以及是否是文件
    if not os.path.isfile(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path, media_type='image/jpeg')


@view.get("/view_detect_thumb/{image_id}")
def view_detect_thumb(image_id: int, session: Session = Depends(get_db)):
    """
    查看图片
    :param session:
    :param image_id: 图片id
    :return:
    """
    sour_url, thumb_url = get_detect_img_url(image_id, session)
    image_path = os.path.join(images_url, thumb_url)
    # 检查文件是否存在以及是否是文件
    if not os.path.isfile(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path, media_type='image/jpeg')


@view.get("/view_log_img/{image_id}")
def view_log_img(image_id: int, session: Session = Depends(get_db)):
    """
    查看推理完成后图片
    :param session:
    :param image_id: 图片id
    :return:
    """
    url = get_log_img_url(image_id, session)
    image_path = os.path.join(url)
    # 检查文件是否存在以及是否是文件
    if not os.path.isfile(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path, media_type='image/jpeg')


