from datetime import timedelta, date

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 rest_framework_simplejwt.tokens import RefreshToken

from config.settings.base import DEFAULT_FROM_EMAIL
from verify_trusted.companies.models import Subscription, Company
from verify_trusted.users.tasks import send_email

User = get_user_model()


def send_activation_email(email):
    user = User.objects.get(email=email)
    token = RefreshToken.for_user(user).access_token
    token.set_exp(lifetime=timedelta(minutes=5))
    active_url = '{}?token={}'.format(settings.USER_ACTIVATION_URL, str(token))
    if settings.IS_PRODUCTION:
        send_to_email = [user.email]
    else:
        send_to_email = settings.DEFAULT_SEND_TO_EMAIL
    email_context = {'email': user.email, 'url': active_url}
    rendered = render_to_string('users/email/email_confirm.html', context=email_context)
    msg = EmailMultiAlternatives(
        # title:
        'Active user on {title}'.format(title='Verify Trusted'),
        # message:
        'Active User',
        # from:
        DEFAULT_FROM_EMAIL,
        # to:
        send_to_email,
        bcc=['info@verifytrusted.com', 'verifytrusted.support@sphinxjsc.com'],
    )
    msg.attach_alternative(rendered, 'text/html')
    msg.send()


def send_welcome_email(email):
    print('send email')
    fields = ['name', 'email', 'name']
    email_1_days = User.objects.filter(email=email).values_list(*fields).distinct()
    send_email(email_1_days, "users/email/day1_tpl.html", "Welcome to VerifyTrusted!", "name")


def send_cancel_email(email, url):
    if settings.IS_PRODUCTION:
        send_to_email = ['admin@verifytrusted.com']
        url_preset = 'https://www.verifytrusted.com/reviews/'
    else:
        send_to_email = ['doanthanh58863@gmail.com']
        url_preset = 'https://test.verifytrusted.net/reviews/'
    email_context = {'email': email, 'url': url_preset+url}
    print('send email cancel')
    print(f'Number of emails: {send_to_email, url_preset+url}')
    rendered = render_to_string('users/email/email_account_deactive.html', context=email_context)
    msg = EmailMultiAlternatives(
        # title:
        'Request cancel account',
        # message:
        '',
        DEFAULT_FROM_EMAIL,
        # to:
        send_to_email,
        bcc=[],
    )
    msg.attach_alternative(rendered, 'text/html')
    msg.send()

