import uuid
from typing import Any, Annotated, Optional
from app.utils import validate_file_size_type, save_picture, del_picture
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from sqlmodel import func, select

from app.api.deps import CurrentUser, SessionDep
from app.models import (
    Info_Image,
    Info_ImageCreate,
    Message,
    Course,
    CoursePublicWithImages
)

router = APIRouter()

@router.post("/",response_model=CoursePublicWithImages)
async def create_info_image(
    *, session: SessionDep, current_user: CurrentUser,
    image: Annotated[UploadFile, File()],
    index: int = Form(),
    course_id: uuid.UUID = Form(),
) -> Any:
    """
    Create new image.
    """
    validate_file_size_type(image)
    imageUrl =  await save_picture(file=image, folder_name="tmp")
    info_image_in = Info_ImageCreate(image=imageUrl, index=index, course_id=course_id)
    info_image = Info_Image.from_orm(info_image_in)
    session.add(info_image)
    session.commit()
    session.refresh(info_image)
    course = session.get(Course, course_id)
    return course

@router.put("/{id}",response_model=CoursePublicWithImages)
async def edit_info_image(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    id: uuid.UUID,
    index: int,
)-> Any:
    info_image = session.get(Info_Image, id)
    info_image_in = Info_ImageCreate(image=info_image.image, index=index, course_id=info_image.course_id)
    update_dict = info_image_in.model_dump(exclude_unset=True)
    info_image.sqlmodel_update(update_dict)
    session.add(info_image)
    session.commit()
    session.refresh(info_image)
    course = session.get(Course, info_image.course_id)
    return course

@router.delete("/{id}",response_model=CoursePublicWithImages)
async def delete_info_image(
    *,
    session: SessionDep,
    current_user: CurrentUser,
    id: uuid.UUID,
)-> Any:
    info_Image = session.get(Info_Image, id)
    await del_picture(info_Image.image)
    session.delete(info_Image)
    session.commit()
    course = session.get(Course, info_Image.course_id)
    return course
