from django.shortcuts import render
from django_tables2 import RequestConfig
from .models import Speaker, LegislativeInfo, LegislativeInstitution
from speeches.models import Speech
from .tables import SpeakerTable
from speeches.tables import SpeakerSpeechTable
from django.http import Http404
from watson import search as watson
from .forms import SearchForm
from speeches.forms import SearchFormSpeech


def speakers(request):
    """
    This view creates the page for the searchable speakers list.
    """
    if(request.method == "GET"):
        form = SearchForm(request.GET)
        if(form.is_valid()):
            query = form.cleaned_data["query"]
            search_results = watson.filter(Speaker, query)
            table = SpeakerTable(search_results)
            RequestConfig(request, paginate={'per_page': 20}).configure(table)
            context = {"title": "Suchergebnisse für " + query,
                       "form": form, "table": table}
            return render(request, "speakers/speakers.html", context)
        else:
            form = SearchForm()
            table = SpeakerTable(Speaker.objects.all().order_by("last_name"))
            RequestConfig(request, paginate={'per_page': 20}).configure(table)
            context = {"title": "Suche", "table": table, "form": form}
            return render(request, "speakers/speakers.html", context)


def speaker(request, id):
    """
    This view creates the profile page of one speaker.
    """
    try:
        current_speaker = Speaker.objects.get(pk=id)
        speech_count = len(Speech.objects.filter(foreign_speaker=id))
        current_legislative_info = LegislativeInfo.objects.filter(foreign_speaker=id)
        sorted_l_info = current_legislative_info.order_by("legislative_period")
        institution_info = LegislativeInstitution.objects.filter(foreign_speaker=id)
        sorted_i_info = institution_info.order_by("current_period")
        table = SpeakerSpeechTable(Speech.objects.filter(foreign_speaker=id))
        RequestConfig(request, paginate={'per_page': 20}).configure(table)
    except Speaker.DoesNotExist:
        raise Http404("Speaker does not exist")
    context = {"title": ("MdB – "
                         + current_speaker.first_name
                         + " " + current_speaker.last_name),
               "current_speaker": current_speaker,
               "sorted_l_info": sorted_l_info,
               "sorted_i_info": sorted_i_info,
               "speech_table": table,
               "speech_count": speech_count}
    return render(request, "speakers/speaker.html", context)
