from django.urls import path
from django.http import HttpResponse
from tournaments.models import CustomUser
from tournaments.models.enums import UserOrigin
from django.core.mail import send_mail

import time

def users_list(with_tournaments):
    return CustomUser.objects.filter(origin=UserOrigin.APP).exclude(purchase__isnull=False).filter(events__isnull=with_tournaments)

def email_users_with_tournaments_count(request):
    users = users_list(False)
    emails = [user.email for user in users]
    return HttpResponse(f'users = {len(users)}, \n\nemails = {emails}')

def email_users_count(request):
    users = users_list(True)
    emails = [user.email for user in users]
    return HttpResponse(f'users = {len(users)}, \n\nemails = {emails}')

def email_users_view(request):
    return email_users(request, users_list(True), 0)

def email_users_with_tournaments(request):
    return email_users(request, users_list(False), 1)

def email_users(request, users, template_index):

    users = users_list(True)

    subject = 'check Padel Club'
    from_email = 'laurent@padelclub.app'

    sent_count = 0
    error_emails = []
    all_emails = []

    for user in users:
        mail_body = template(user, template_index) # f'Bonjour {user.first_name}, cool la vie ?'
        all_emails.append(user.email)

        try:
            send_mail(
                subject,
                mail_body,
                from_email,
                [user.email],
                fail_silently=False,
            )
            sent_count += 1
        except Exception as e:
            error_emails.append(user.email)

        time.sleep(1)

    return HttpResponse(f'users = {len(users)}, sent = {sent_count}, errors = {len(error_emails)}, \n\nemails = {all_emails}, \n\nerror emails = {error_emails}')

def template(user, index):
    if index == 0:
        return f'Bonjour {user.first_name}, \n\n'
    else:
        return f'Bonjour {user.first_name}, \n\nJe te remercie d\'avoir téléchargé Padel Club. J\'ai pu voir que tu avais créé quelques tournois mais sans aller plus loin, est-ce que tu pourrais me dire ce qui t\'as freiné ?\n\nLaurent Morvillier'

urlpatterns = [
    path('email_users/', email_users_view, name='biz_email_users'),
    path('email_users_count/', email_users_count, name='biz_email_count'),
    path('email_users_with_tournaments_count/', email_users_with_tournaments_count, name='biz_email_with_tournaments_count'),
    path('email_users_with_tournaments/', email_users_with_tournaments, name='email_users_with_tournaments'),
]
