from json import dumps

from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework.generics import ListAPIView, RetrieveAPIView

from .docsimserver import DocSimServer
from .models import Cluster, Document
from .serializers import ClusterSerializer  # , DocumentSerializer

ACCEPTED = 202


@csrf_exempt
@require_POST
def add_or_update(request):
    id = request.POST.get('id')
    text = request.POST.get('text')
    if id and text:
        Document(id=id, text=text).save()
        return HttpResponse(status=ACCEPTED)
    else:
        return HttpResponseBadRequest()


class ClusterList(ListAPIView):
    model = Cluster
    serializer_class = ClusterSerializer


class ClusterDetail(RetrieveAPIView):
    model = Cluster
    serializer_class = ClusterSerializer


@require_POST
def find_similar(request):
    id = request.POST.get('id')
    text = request.POST.get('text')
    if not text:
        return HttpResponseBadRequest()
    doc = Document(id=id, text=text)
    dss = DocSimServer()
    similar = dss.find_similar({'tokens': doc.tokens()}, max_results=10)
    return HttpResponse(content=dumps(similar), content_type='text/json')

# maybe later
#
#    if id:
#        doc.save()
#        dss.server.index([{'id': id, 'tokens': tokens}])

@@ -891,16 +891,29 @@
 lizer%0A%0A%0A
+@csrf_exempt%0A
 @require
@@ -914,24 +914,24 @@
 equire_POST%0A
-
 def find_sim
@@ -953,86 +953,182 @@
     
-id = request.POST.get('id')%0A    text = request.POST.get('text')%0A    if not tex
+try:%0A        text = request.POST%5B'text'%5D%0A        min_score = float(request.POST.get('min_score', .8))%0A        max_results = int(request.POST.get('max_results', 10))%0A    excep
 t:%0A 
@@ -1166,16 +1166,48 @@
 quest()%0A
+    id = request.POST.get('id')%0A
     doc 
@@ -1318,16 +1318,80 @@
 ns()%7D, m
+in_score=min_score,%0A                               max_results=m
 ax_resul
@@ -1396,11 +1396,8 @@
 ults
-=10
 )%0A  

add csrf_exempt, min_score and max_results to documents.views.find_similar