import os
import time
from wordcloud import WordCloud, STOPWORDS

from django.conf import settings
from gauth.models import Location
from review.models import Review
from facebook_app.models import FacebookReview


WC = WordCloud(
    width=1200,
    height=300,
    background_color='white',
    stopwords=STOPWORDS
)
GOOGLE_PATH = os.path.join(settings.BASE_DIR, 'media', 'google')
FACEBOOK_PATH = os.path.join(settings.BASE_DIR, 'media', 'facebook')


def create_wc_for_google(location_id):
    reviews = Review.objects.filter(location_id=location_id).exclude(comment=None)
    pos_reviews = reviews.filter(star_rating__gte=4)[:100]
    neg_reviews = reviews.filter(star_rating__lte=3)[:100]
    pos_text = ' '.join([review.comment for review in pos_reviews])
    neg_text = ' '.join([review.comment for review in neg_reviews])
    if len(pos_text) == 0:
        pos_text = "No positive Review found."
    if len(neg_text) == 0:
        neg_text = "No negative Review found."
    wc = WC.generate_from_text(pos_text)
    wc.to_file(GOOGLE_PATH+'/positive/'+f'{location_id}.png')
    wc = WC.generate_from_text(neg_text)
    wc.to_file(GOOGLE_PATH+'/negative/'+f'{location_id}.png')


def create_wc_for_facebook(location_id):
    reviews = FacebookReview.objects.filter(page__location_id=location_id).exclude(review_text=None)
    pos_reviews = reviews.filter(recommendation_type=True)[:100]
    neg_reviews = reviews.filter(recommendation_type=False)[:100]
    pos_text = ' '.join([review.review_text for review in pos_reviews])
    neg_text = ' '.join([review.review_text for review in neg_reviews])
    if len(pos_text) == 0:
        pos_text = "Didn't found posted any positive Review."
    if len(neg_text) == 0:
        neg_text = "Didn't found posted any negative Review."
    wc = WC.generate_from_text(pos_text)
    wc.to_file(FACEBOOK_PATH+'/positive/'+f'{location_id}.png')
    wc = WC.generate_from_text(neg_text)
    wc.to_file(FACEBOOK_PATH+'/negative/'+f'{location_id}.png')


def generate_word_clouds():
    locations = Location.objects.all()
    start = time.time()
    for loc in locations:
        create_wc_for_google(location_id=loc.location_id)
        create_wc_for_facebook(location_id=loc.location_id)
    end = time.time()
    print('Elapsed time: ', end-start, 'millisecond.')