from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect
from review.forms import ReplyForm
from review.models import Review, CustomReply
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required


from .nlu_utils import (
    model_inference,
    analyze_model_inference,
    filter_with_last_ten_reviews
)


@login_required
def predict_report(request, review_id):
    review = Review.objects.get(review_id=review_id)
    location_type = review.location.organization
    location_id = review.location_id
    replies = {}
    if review.star_rating == 5:
        text = review.comment.lower()
        res = model_inference(text=text)
        intents = analyze_model_inference(res)
        for intent in intents.keys():
            r = CustomReply.objects.filter(reply_category=intent, organization=location_type)
            filtered_replies = filter_with_last_ten_reviews(location_id, r)
            replies[intent] = filtered_replies

    elif review.star_rating == 4:
        intents = {'four_star': 100}
        cr = CustomReply.objects.filter(reply_star=4, organization=location_type)
        filtered_replies = filter_with_last_ten_reviews(location_id, cr)
        replies = {'four_star': filtered_replies}

    elif review.star_rating == 3:
        intents = {'three_star': 100}
        cr = CustomReply.objects.filter(reply_star=3, organization=location_type)
        filtered_replies = filter_with_last_ten_reviews(location_id, cr)
        replies = {'three_star': filtered_replies}

    else:
        intents = {'negative': 100}
        cr = CustomReply.objects.filter(reply_star__lte=2, organization=location_type)
        filtered_replies = filter_with_last_ten_reviews(location_id, cr)
        replies = {'negative': filtered_replies}

    now = timezone.now()
    form = ReplyForm()
    date = now - timezone.timedelta(days=30)
    hours = now - timezone.timedelta(hours=6)
    reviews = Review.objects.filter(reply=None, update_time__gte=date, location__organization=location_type)\
        .exclude(comment=None, star_rating=5)\
        .exclude(star_rating__lte=3, update_time__gte=hours)\
        .order_by('update_time')
    page = request.GET.get('page', 1)
    paginator = Paginator(reviews, 10)
    try:
        reviews = paginator.page(page)
    except PageNotAnInteger:
        reviews = paginator.page(1)
    except EmptyPage:
        reviews = paginator.page(paginator.num_pages)

    context = {
        'reviews': reviews,
        'form': form,
        'intents': intents,
        'replies': replies,
    }
    return render(request, 'dashboard.html', context)