from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.generic import View
from django.contrib.auth.mixins import LoginRequiredMixin

from gauth.models import Location
from name_extractor.models import Staff
from yelp.analytics import get_yelp_weekly_summary
from facebook_app.analytics import get_facebook_weekly_summary

from .utils import (
    get_review_count_by_month,
    get_review_count_by_week,
    last_month_reviews,
    weekly_reviews_summary
)


class ChartDataByMonth(APIView):
    def get(self, request, *args, **kwargs):
        location_id = request.GET['location_id']
        time_interval = request.GET['time_interval']
        if time_interval == 'month':
            res = get_review_count_by_month(location_id)
        else:
            res = get_review_count_by_week(location_id)
        return Response(res)


class AnalyticsData(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        locations = Location.objects.all()
        return render(request, 'charts.html', {'location_list': locations})


def monthly_report(requests, location_id):
    last_month_data = last_month_reviews(location_id=location_id)

    staffs = Staff.objects.filter(location_id=location_id).\
        exclude(name_mentioned=0).order_by('-total_units')

    context = {

        'this_month': last_month_data,
        'staffs': staffs
    }
    return render(requests, 'last_month_report.html', context)


def weekly_report(requests, location_id):
    g_reviews, g_ratings = weekly_reviews_summary(location_id=location_id)
    y_reviews, y_ratings = get_yelp_weekly_summary(location_id=location_id)
    f_reviews, f_ratings = get_facebook_weekly_summary(location_id=location_id)

    g_bad_reviews = g_reviews.filter(star_rating__lte=2)
    y_bad_reviews = y_reviews.filter(rating__lte=2)
    f_bad_reviews = f_reviews.filter(recommendation_type=False)

    context = {

        'google_ratings': g_ratings,
        'google_bad_reviews': g_bad_reviews,
        'yelp_ratings': y_ratings,
        'yelp_bad_reviews': y_bad_reviews,
        'facebook_ratings': f_ratings,
        'facebook_bad_reviews': f_bad_reviews
    }
    return render(requests, 'weekly_report.html', context)