import random
from threading import Thread
from time import sleep
from django.utils import timezone
from .models import Review, CustomReply
from nlu_job.nlu_utils import is_a_name
from review.review_utils import reply_review


def un_replied_reviews_with_no_comment():
    now = timezone.now()
    date = now - timezone.timedelta(days=30)
    reviews = Review.objects.filter(comment=None, reply=None, star_rating=5, update_time__gte=date).order_by('update_time')
    return reviews


def generate_reply(review):
    replies = CustomReply.objects.filter(reply_category='no_comment')
    reply = random.choice(replies)
    name = review.reviewer_name
    if is_a_name(name):
        parsable_name = ', '+name.split()[0].capitalize()
    else:
        parsable_name = ''
    replied_text = reply.reply %parsable_name
    return replied_text


def task():
    while True:
        reviews = un_replied_reviews_with_no_comment()
        # TODO: reply reviews in background
        for review in reviews:
            replied_text = generate_reply(review)
            response = reply_review(review=review, replied_text=replied_text)

            if response.status_code == 200:
                print(f'Reply for {review.reviewer_name}\'s comment in {review.location} has successfully done!')

        sleep(60*random.randint(2, 5))


thread = Thread(target=task)
# thread.start()
