from django.shortcuts import render, get_object_or_404
from poetry.models import Poet, Poem


def new(request, slug=None):
    if slug is not None:
        poet = get_object_or_404(Poet, slug=slug)
    else:
        poet = Poet.objects.order_by('?')[0]

    poem = poet.write()
    return render(request, "poetry/poem.html", locals())


def poem(request, slug):
    poem = get_object_or_404(Poem, slug=slug)
    return render(request, "poetry/poem.html", locals())


def poet(request, slug):
    poet = get_object_or_404(Poet, slug=slug)
    last = poet.poem_set.order_by('-created_at')[:20]
    in_contest = poet.poem_set.filter(in_contest=True).order_by('created_at')
    return render(request, "poetry/poet.html", locals())


def main(request):
    poets = Poet.objects.all().order_by('?')
    last = Poem.objects.all().order_by('-created_at')[:20]
    return render(request, "poetry/main.html", locals())


def contest(request):
    poets = Poet.objects.all().order_by('?')
    return render(request, "poetry/contest.html", locals())

