import fastapi as fa
import jinja2
from starlette import responses
from ebookwords import core


environment = jinja2.Environment(
    loader=jinja2.PackageLoader("ebookwords", "interface/web/ebook")
)
router = fa.APIRouter()


@router.post("/upload", response_class=responses.RedirectResponse)
def upload_file(
    uploaded_files: list[fa.UploadFile] = fa.File(),
    book_manager: core.BookManager = fa.Depends(core.get_book_manager),
):
    for upload_file in uploaded_files:
        book_manager.store_ebook(upload_file.file)
    return responses.RedirectResponse(url="/", status_code=303)


@router.get("/", response_class=responses.HTMLResponse)
def list_ebooks(
    book_manager: core.BookManager = fa.Depends(core.get_book_manager),
):
    ebooks = book_manager.db_client.get_book_list()
    template = environment.get_template("ebook_list.html")
    html = template.render(ebooks=ebooks)
    return html


@router.get("/{ebook_id}/", response_class=responses.HTMLResponse)
def list_chapters(
    ebook_id: int,
    book_manager: core.BookManager = fa.Depends(core.get_book_manager),
):
    ebook = book_manager.db_client.get_book(ebook_id)
    if ebook is None:
        raise Exception()

    chapters = book_manager.db_client.get_chapter_list(ebook_id)
    template = environment.get_template("chapter_list.html")
    html = template.render(chapters=chapters)
    return html


@router.get("/{ebook_id}/{chapter_number}/", response_class=responses.HTMLResponse)
def show_chapter(
    ebook_id: int,
    chapter_number: int,
    book_manager: core.BookManager = fa.Depends(core.get_book_manager),
):
    paragraphs = book_manager.db_client.get_chapter_paragraphs(ebook_id, chapter_number)
    template = environment.get_template("chapter.html")
    html = template.render(title="", paragraphs=paragraphs)
    return html
