from django.shortcuts import render
from django_tables2 import RequestConfig
from .models import Speech, Protocol
from .tables import SpeechTable, ProtocolTable
from django.http import Http404
from .utils import create_html_speech
from .forms import SearchForm, SearchFormSpeech
from watson import search as watson
from collections import Counter


def speech(request, speech_id):
    """
    This view creates the page of one speech.
    """
    try:
        current_speech = Speech.objects.get(pk=speech_id)
        if(current_speech.previous_speech_id is not None):
            previous_speech = Speech.objects.get(pk=current_speech.previous_speech_id)
            previous_speech_html = create_html_speech(previous_speech.speech_content)[0]
        else:
            previous_speech = None
            previous_speech_html = None
        if(current_speech.next_speech_id is not None):
            next_speech = Speech.objects.get(pk=current_speech.next_speech_id)
            next_speech_html = create_html_speech(next_speech.speech_content)[0]
        else:
            next_speech = None
            next_speech_html = None
        current_speech_html, raw_text, interruptions = create_html_speech(current_speech.speech_content)
        vocabulary = Counter(raw_text.split()).most_common()
        unique_words = len(vocabulary)
        tmp_str = []
        for pair in vocabulary:
            tmp_str.append("<li>{}: {}</li>".format(pair[0], pair[1]))
        vocabulary = "".join(tmp_str)
    except Speech.DoesNotExist:
                raise Http404("Speech does not exist")
    context = {"title": ("Rede – "
                         + " "
                         + current_speech.speech_id),
               "current_speech": current_speech,
               "current_speech_html": current_speech_html,
               "previous_speech_html": previous_speech_html,
               "next_speech_html": next_speech_html,
               "previous_speech": previous_speech,
               "next_speech": next_speech,
               "interruptions": interruptions,
               "words": len(raw_text.split()),
               "vocabulary": vocabulary,
               "unique_words": unique_words}
    return render(request, "speeches/speech.html", context)


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


def protocol(request, protocol_id):
    """
    This view creates the page of one protocol.
    """
    try:
        current_protocol = Protocol.objects.get(pk=protocol_id)
        related_speeches = Speech.objects.filter(foreign_protocol=protocol_id).order_by("speech_id")
        speakers = []
        speeches_html = []
        for speech in related_speeches:
            speakers.append(speech.foreign_speaker)
            speech_html = create_html_speech(speech.speech_content)[0]
            speeches_html.append(speech_html)
        speaker_speech_html = zip(speakers, speeches_html, related_speeches)
    except Protocol.DoesNotExist:
                raise Http404("Protocol does not exist")
    context = {"title": ("Protokoll – " + str(current_protocol.protocol_id)),
               "current_protocol": current_protocol,
               "related_speeches": related_speeches,
               "speeches_html": speeches_html,
               "speakers": set(speakers),
               "speaker_speech_html": speaker_speech_html}
    return render(request, "speeches/protocol.html", context)


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