from django.shortcuts import render, get_object_or_404
from .models import PublicBody, Party, Member, Question, Vote


def home(request):
    return render(request, "index.html", {})


def public_bodies(request):
    items = PublicBody.objects.all()
    return render(request, "council/public_bodies.html", {"items": items})


def public_body_detail(request, slug: str):
    body = get_object_or_404(PublicBody, slug=slug)
    members = body.members.select_related("party").all()
    parties = Party.objects.filter(members__public_body=body).distinct()
    votes = body.votes.all()
    return render(
        request,
        "council/public_body_detail.html",
        {"body": body, "members": members, "parties": parties, "votes": votes},
    )


def members(request):
    items = Member.objects.select_related("public_body", "party").all()
    return render(request, "council/members.html", {"items": items})


def member_detail(request, pk: int):
    member = get_object_or_404(Member.objects.select_related("public_body", "party"), pk=pk)
    questions = member.questions.all()
    votes = member.votes.select_related("public_body").all()
    return render(
        request,
        "council/member_detail.html",
        {"member": member, "questions": questions, "votes": votes},
    )


def parties(request):
    items = Party.objects.all()
    return render(request, "council/parties.html", {"items": items})


def party_detail(request, pk: int):
    party = get_object_or_404(Party, pk=pk)
    members = party.members.select_related("public_body").all()
    public_bodies = PublicBody.objects.filter(members__party=party).distinct()
    questions = Question.objects.filter(member__party=party).select_related("member").all()
    return render(
        request,
        "council/party_detail.html",
        {"party": party, "members": members, "public_bodies": public_bodies, "questions": questions},
    )


def questions(request):
    items = Question.objects.select_related("member").all()
    return render(request, "council/questions.html", {"items": items}) 