from django.db.models import Count
from django.utils import timezone
from .models import YelpReview
from analytics.background_job import send_email
from gauth.models import Location
from django.conf import settings


def get_yelp_weekly_summary(location_id):
    date = timezone.now() - timezone.timedelta(days=7)
    reviews = YelpReview.objects.filter(location__location_id=location_id, date_posted__gte=date)
    rating = reviews.values('rating').annotate(total=Count('rating')).order_by('-rating')
    return reviews, rating


def send_email_bad_reviews():
    locations = Location.objects.all()
    for location in locations:
        to = settings.ADMIN_MAINTAINER_EMAILS
        date = timezone.now() - timezone.timedelta(hours=12)
        reviews = YelpReview.objects.filter(
            location__location_id=location.location_id,
            date_posted__gte=date,
            rating__lte=3
        )
        total_reviews = reviews.count()
        if total_reviews > 0:
            # Add location maintainer email if it has an email
            to.append(location.recipient_email) if location.recipient_email else None

            subject = f"A negative Yelp review has been post in {location.care_name}."
            message = f'''
            <p>Hi there, </p>
            <p>'''
            if total_reviews > 1:
                tt = f'{total_reviews} negative Yelp reviews have'
            else:
                tt = f'A negative Yelp review has '
            message += tt + f'been posted in {location.care_name}.</p>'
            for r in reviews:
                link = f'<p>Link: {r.location.url}</p>'
                name = f'<p><b>Reviewer Name:</b> {r.reviewer_name}</p>'
                rating = f'<p style="color: red"><b>Rating:</b> {str(r.rating)} star rating.</p>'
                comment = f'<p><b>Comment: </b>{r.comment if r.comment else "No comment"}</p>'
                message += name + rating + comment + link
            message += '<p>Regards,</p><p>Byte Trek Ltd.</p>'

            send_email(to_list=to, subject=subject, message=message)
            if location.recipient_email in to:
                to.remove(location.recipient_email)