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 (
    Image,
    ImageCreate,
    Message,
    Course,
    CoursePublicWithImages
)

router = APIRouter()

@router.post("/",response_model=CoursePublicWithImages)
async def create_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")
    image_in = ImageCreate(image=imageUrl, index=index, course_id=course_id)
    image = Image.from_orm(image_in)
    session.add(image)
    session.commit()
    session.refresh(image)
    course = session.get(Course, course_id)
    return course

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

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