from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload

from dependencies import get_current_user, get_db
from models.tag import Tag, TagKategorie

router = APIRouter(prefix="/tags")
templates = Jinja2Templates(directory="templates")


@router.get("", response_class=HTMLResponse)
async def verwaltung(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
    kategorien = (
        db.query(TagKategorie)
        .options(joinedload(TagKategorie.tags).joinedload(Tag.kontakte))
        .order_by(TagKategorie.sortierung, TagKategorie.name)
        .all()
    )
    return templates.TemplateResponse("pages/tags/verwaltung.html", {
        "request": request,
        "user": user,
        "active_page": "tags",
        "kategorien": kategorien,
    })


@router.post("/kategorie/neu")
async def kategorie_erstellen(
    name: str = Form(...),
    farbe: str = Form("#607D8B"),
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    kat = TagKategorie(name=name, farbe=farbe)
    db.add(kat)
    db.commit()
    return RedirectResponse(url="/tags", status_code=303)


@router.post("/neu")
async def tag_erstellen(
    name: str = Form(...),
    kategorie_id: int = Form(...),
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    tag = Tag(name=name, kategorie_id=kategorie_id)
    db.add(tag)
    db.commit()
    return RedirectResponse(url="/tags", status_code=303)
