from fastapi import APIRouter, Request, status, Form
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse

from src.db.models.comic import Artist
from typing import AnyStr

from src.db.repository.comics.artist import update_artist
from src.db.session import SessionDep
#from src.db.repository.comic import create_new_worktype, update_worktype
from src.main import logger
from src.schema.comics.artist import AddArtist
from src.webapps.comic.forms.artist import AddArtistForm

#from src.schema.comics.worktype import AddWorkType
#from src.webapps.comic.forms import AddWorktypeForm

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

@router.get("/artists")
def get_artists(db: SessionDep, request: Request, msg: str | None = None):
    artists = db.query(Artist).all()
    return templates.TemplateResponse("comic/artists.html", {"request": request, "msg": msg, "artists": artists})

@router.get("/artists/{artist_id}")
def artist_detail(artist_id: AnyStr, request: Request, db: SessionDep):
    artist = db.get(Artist, str(artist_id))
    return templates.TemplateResponse("comic/artist_detail.html", {"request": request, "artist": artist})


@router.get("/artist/edit/{artist_id}")
def edit_artist(db: SessionDep, request: Request, artist_id: str):
    artist = db.get(Artist, artist_id)
    return templates.TemplateResponse("comic/artist_edit.html", {"request": request, "artist_name": artist.name, "artist_link": artist.weblink})

@router.post("/artist/edit/{artist_id}")
async def edit_artist(request: Request, db: SessionDep, artist_id: str, action: str = Form(...), artist_name: str = Form(...), artist_link: str = Form(...)):
    if action == "cancel":
        return RedirectResponse(f"/comic/artists/{artist_id}", status_code=status.HTTP_303_SEE_OTHER)
    form = AddArtistForm(request, artist_id, artist_name, artist_link)
    await form.load_data()
    if form.is_valid():
        try:
            artist = AddArtist(**form.__dict__)
            artist = update_artist(add_artist=artist, artist_id=artist_id, db=db)
            return RedirectResponse(f"/comic/artists/{artist.id}", status_code=status.HTTP_303_SEE_OTHER)
        except Exception as e:
            print(e)
            form.__dict__.get("errors").append("artist already added")
            return templates.TemplateResponse("comic/artist_edit.html", form.__dict__)
    return templates.TemplateResponse("comic/artist_edit.html", form.__dict__)

@router.get("/artist/delete/{artist_id}")
async def delete_artist(db: SessionDep, request: Request, artist_id: str):
    artist = db.get(Artist, artist_id)
    db.delete(artist)
    db.commit()
    return RedirectResponse("/comic/artists", status_code=status.HTTP_303_SEE_OTHER)
