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

from src.db.models.comic import Comic, Publisher, Issue
from typing import AnyStr
from src.core.log_conf import logger
from src.db.repository.comics.comic import update_comic
from src.db.session import SessionDep
from src.schema.comics.comic import ComicSchema
from src.webapps.comic.forms.comic import ValidateComicForm

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

@router.get("/comics")
def get_comics(db: SessionDep, request: Request, msg: str | None = None):
    params = request.query_params
    query = params.get("query")
    filter = {}
    completed = params.get('completed') == "on"
    if completed:
        filter['completed'] = True
    order = params.get("order") == "on"
    if order:
        filter['current_order'] = True
    if query is not None and len(query) > 0:
        filter['title'] = query
    if len(filter) > 0:
        if "title" in filter:
            comics  = db.query(Comic).filter(Comic.title.ilike(f'%{query}%'))
        else:
            comics = db.query(Comic).filter_by(**filter).all()
    else:
        comics = db.query(Comic).all()
    return templates.TemplateResponse("comic/comics.html", {"request": request, "msg": msg, "comics": comics})

@router.get("/comics/{comic_id}")
def comic_details(comic_id: AnyStr, request: Request, db: SessionDep):
    comic = db.get(Comic, comic_id)
    return templates.TemplateResponse("comic/comic_detail.html", {"request": request, "comic":comic})

@router.get("/comic/edit/{comic_id}")
def edit_comic(db: SessionDep, request: Request, comic_id: str):
    comic = db.get(Comic, comic_id)
    return templates.TemplateResponse("comic/comic_edit.html", {"request": request, "comic_title": comic.title, "comic_weblink": comic.weblink})



@router.post("/comic/edit/{comic_id}")
async def validate_comic(request: Request, db: SessionDep, comic_id: str, action: str = Form(...), completed: bool = Form(False), current_order: bool = Form(False)):
    if action == "cancel":
            return RedirectResponse(f"/comic/comics/{comic_id}", status_code=status.HTTP_303_SEE_OTHER)
    form = ValidateComicForm(request, comic_id, completed, current_order)
    logger.info(f"request: {repr(request)}")
    await form.load_data()
    logger.info(f"form: {form}")
    if form.is_valid():
        try:
            comic = ComicSchema(**form.__dict__)
            comic = update_comic(new_comic=comic, comic_id=comic_id, db=db)
            return RedirectResponse(f"/comic/comics/{comic.id}", status_code=status.HTTP_303_SEE_OTHER)
        except Exception as e:
            print(e)
            form.__dict__.get("errors").append("comic already added")
            return templates.TemplateResponse("comic/comic_edit.html", form.__dict__)
    return templates.TemplateResponse("comic/comic_edit.html", form.__dict__)

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

@router.get("/publishers/{publisher_id}")
def publisher_details(publisher_id: AnyStr, request: Request, db: SessionDep, msg: str = None):
    publisher = db.get(Publisher, publisher_id)
    if publisher is None:
        msg = "Could not find Publisher"
    return templates.TemplateResponse("comic/publisher_detail.html", {"request": request, "msg": msg, "publisher": publisher})

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

@router.get("/issues/{issue_id}")
def issue_details(issue_id: AnyStr, request: Request, db: SessionDep):
    issue = db.get(Issue, issue_id)
    return templates.TemplateResponse("comic/issue_detail.html", {"request": request, "issue": issue})

