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

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

from src.db.repository.comics.worktype import create_new_worktype, update_worktype
from src.db.session import SessionDep
from src.main import logger
from src.schema.comics.worktype import AddWorkType
from src.webapps.comic.forms.worktype import AddWorktypeForm

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

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

@router.get("/worktypes/{worktype_id}")
def worktype_detail(db: SessionDep, request: Request, worktype_id: AnyStr):
    worktype = db.get(WorkType, worktype_id)
    return templates.TemplateResponse("comic/worktype_detail.html", {"request": request, "worktype": worktype})

@router.get("/worktype/add")
def add_worktype(request: Request, db: SessionDep):
    return templates.TemplateResponse("comic/worktype_edit.html", {"request": request})

@router.post("/worktype/add")
async def add_worktype_post(db: SessionDep, request: Request):
    form = AddWorktypeForm(request)
    await form.load_data()
    if form.is_valid():
        try:
            work = AddWorkType(**form.__dict__)
            worktype = create_new_worktype(work=work, db=db)
            logger.info(f"add_worktype: redirect to /comic/worktypes/{worktype.id}")
            return RedirectResponse(f"/comic/worktypes/{worktype.id}", status_code=status.HTTP_303_SEE_OTHER)
        except Exception as e:
            print(e)
            form.__dict__.get("errors").append("worktype already added")
            return templates.TemplateResponse("comic/worktype_edit.html", form.__dict__)
    print("form is not valid")
    return templates.TemplateResponse("comic/worktype_edit.html", form.__dict__)

@router.get("/worktype/edit/{worktype_id}")
def edit_worktype(db: SessionDep, request: Request, worktype_id: str):
    worktype: WorkType | None = db.get(WorkType, worktype_id)
    return templates.TemplateResponse("comic/worktype_edit.html", {"request": request, "worktype": worktype.name})

@router.post("/worktype/edit/{worktype_id}")
async def edit_worktype_post(request: Request, db: SessionDep, worktype_id: str):
    form = AddWorktypeForm(request)
    await form.load_data()
    if form.is_valid():
        try:
            work = AddWorkType(**form.__dict__)
            worktype = update_worktype(work=work, worktype_id=worktype_id, db=db)
            return RedirectResponse(f"/comic/worktypes/{worktype.id}", status_code=status.HTTP_303_SEE_OTHER)
        except Exception as e:
            print(e)
            form.__dict__.get("errors").append("worktype already added")
            return templates.TemplateResponse("comic/worktype_edit.html", form.__dict__)
    return templates.TemplateResponse("comic/worktype_edit.html", form.__dict__)

@router.get("/worktype/delete/{worktype_id}")
async def delete_worktype(db: SessionDep, request: Request, worktype_id: str):
    worktype = db.get(WorkType, worktype_id)
    db.delete(worktype)
    db.commit()
    return RedirectResponse("/comic/worktypes", status_code=status.HTTP_303_SEE_OTHER)
