from django.db.models import Count
from django.utils import timezone
from .models import FacebookReview
from gauth.models import Location, LocationManager
from analytics.background_job import send_email


def get_facebook_weekly_summary(location_id):
    date = timezone.now() - timezone.timedelta(days=7)
    reviews = FacebookReview.objects.filter(page__location_id=location_id, create_time__gte=date)
    rating = reviews.values('recommendation_type')\
        .annotate(total=Count('recommendation_type'))\
        .order_by('-recommendation_type')
    return reviews, rating


def send_email_bad_reviews():
    locations = Location.objects.all()
    for location in locations:
        date = timezone.now() - timezone.timedelta(hours=12)
        # date = timezone.now() - timezone.timedelta(days=20)
        reviews = FacebookReview.objects.filter(
            page__location_id=location.location_id,
            create_time__gte=date,
            recommendation_type=False
        )
        total_reviews = reviews.count()
        if total_reviews > 0:
            # Add location maintainer email if it has an email
            to = list(LocationManager.objects.filter(location_id=location.location_id).values_list('email', flat=True))

            subject = f"A negative Facebook review has been posted in {location.care_name}."
            message = '<p>Hi there, </p><p>'
            if total_reviews > 1:
                tt = f'{total_reviews} negative Facebook reviews have'
            else:
                tt = 'A negative Facebook review has '
            message += tt + f'been posted in {location.care_name}.</p>'
            for r in reviews:
                link = f'<p>Link: https://facebook.com/{r.id}</p>'
                comment = f'<p><b>Comment: </b>{r.review_text if r.review_text else "No comment"}</p>'
                message += comment + link
            message += '<p>Regards,</p><p>SignatureCare Review Team.</p>'
            send_email(subject=subject, message_body=message, to_list=to)