import datetime
from datetime import date, timedelta

from celery.utils.log import get_task_logger
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from config import celery_app
from verify_trusted.companies.models import Subscription, Company
import redis

# REDIS_CLIENT = redis.Redis()
logger = get_task_logger(__name__)

User = get_user_model()


@celery_app.task()
def get_users_count():
    """A pointless Celery task to demonstrate usage."""
    return User.objects.count()

# def check_cached_email(key):
#     if not REDIS_CLIENT.exists(key):
#         print(f"{key} processing ...", flush=True)
#         return False
#     else:
#         print(f"{key} cached ...", flush=True)
#         return True
#
# def cache_email(key):
#     REDIS_CLIENT.set(key, 1)
#     print(REDIS_CLIENT.get(key))


def send_email(emails, email_template_url, title, key=None):
    print(email_template_url)
    print(len(emails))
    for email in emails:
        print(email)
        if email is None:
            print('Email is None')
            break
        if email[0] is None:
            print ('Name is None')
            continue

        # if check_cached_email(f"{email[1]}-{title}-{datetime.datetime.today().strftime('%d/%m/%Y')}"):
        #     print(f"Cached email {email[1]}-{title}-{datetime.datetime.today().strftime('%d/%m/%Y')}")
        #     continue
        # print("Checked cached email")
        prefix = ''
        company_name = ''
        company_url = ''
        if settings.IS_PRODUCTION:
            user_email = [email[1]]
            bcc=['admin@verifytrusted.com']
            url_prefix = "https://www.verifytrusted.com/reviews/"
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            user_email = [email[1]]
            bcc=['verifytrusted.support@sphinxjsc.com', 'doanthanh588@gmail.com', 'trangnh@sphinxjsc.com', 'hantn@sphinxjsc.com']
            url_prefix = "https://test.verifytrusted.net/reviews/"
            from_email = settings.DEFAULT_FROM_EMAIL
        company = Company.objects.filter(user__email=email[1]).first()
        if key == 'name':
            prefix = email[0]+", "
        if key == 'company_name':
            company_name = company.name
            prefix = "Hi " + company.name + ", "
        company_url=company.url
        logger.info('Debug email %s' % email[1])
        email_context = {"name": email[0], "email": email[1], "url": url_prefix + company_url,
                         'is_admin': 0, 'static_url': settings.AWS_S3_CUSTOM_DOMAIN, 'company_name': company_name}
        print("Setup email context")
        
            # user_email = settings.DEFAULT_SEND_TO_EMAIL
        rendered = render_to_string(
            email_template_url, context=email_context
        )
        print(f"Send email to: {user_email}")

        msg = EmailMultiAlternatives(
            # title:
            prefix + title,
            # message:
            '',
            # from:
            from_email,
            # to:
            user_email,
            bcc=bcc,

        )
        print("Setup msg")
        msg.attach_alternative(rendered, 'text/html')
        print("Rendered email")
        msg.send(fail_silently=True)
        print(f'Send reminder to {user_email}')

        # cache_email(f"{email[1]}-{title}-{datetime.datetime.today().strftime('%d/%m/%Y %H:%M')}")
        print("Cached email")
        logger.info(f'Send reminder to {user_email}')



def reminder():
    """A pointless Celery task to demonstrate usage."""
    logger.info('******************** Running reminder ********************')
    fields = ['company__user__name', 'company__user__email', 'company__url']

    # email_10_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(10)).year,
    #                                             create_date__month=(date.today() - timedelta(10)).month,
    #                                             create_date__day=(
    #                                                 date.today() - timedelta(10)).day).values_list(*fields).distinct()

    # email_4_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(4)).year,
    #                                             create_date__month=(date.today() - timedelta(4)).month,
    #                                             create_date__day=(
    #                                                 date.today() - timedelta(4)).day).values_list(*fields).distinct()
    email_2_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(1)).year,
                                            create_date__month=(date.today() - timedelta(1)).month,
                                            create_date__day=(
                                                date.today() - timedelta(1)).day).values_list(*fields).distinct()

    email_3_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(2)).year,
                                            create_date__month=(date.today() - timedelta(2)).month,
                                            create_date__day=(
                                                date.today() - timedelta(2)).day).values_list(*fields).distinct()
    
    email_4_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(3)).year,
                                            create_date__month=(date.today() - timedelta(3)).month,
                                            create_date__day=(
                                                date.today() - timedelta(3)).day).values_list(*fields).distinct()
    
    email_5_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(4)).year,
                                            create_date__month=(date.today() - timedelta(4)).month,
                                            create_date__day=(
                                                date.today() - timedelta(4)).day).values_list(*fields).distinct()

    email_6_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(5)).year,
                                            create_date__month=(date.today() - timedelta(5)).month,
                                            create_date__day=(
                                                date.today() - timedelta(5)).day).values_list(*fields).distinct()                                            

    email_7_days = Subscription.objects.filter(create_date__year=(date.today() - timedelta(7)).year,
                                            create_date__month=(date.today() - timedelta(7)).month,
                                            create_date__day=(
                                                date.today() - timedelta(7)).day).values_list(*fields).distinct()
    if len(email_2_days) > 0:
        send_email(email_2_days, "users/email/day2_tpl.html", "Your VerifyTrusted page is live and ready for you")
    if len(email_3_days) > 0:
        send_email(email_3_days, "users/email/day3_tpl.html", "How to attract customer eyeballs")
    if len(email_4_days) > 0:
        send_email(email_4_days, "users/email/day4_tpl.html", "How to gain customer trust in 27 seconds")
    if len(email_5_days) > 0:
        send_email(email_5_days, "users/email/day5_tpl.html", "How to get more clicks on your reviews")
    if len(email_6_days) > 0:
        send_email(email_6_days, "users/email/day6_tpl.html", "How’s it going?")
    if len(email_7_days) > 0:
        send_email(email_7_days, "users/email/day7_tpl.html", "your 7 day trial has gone fast!", "company_name")
    # if len(email_35_days) > 0:
    #     send_email(email_35_days, "users/email/day_35_no_response.html", "You’ve become Unverified again.")
    return
