from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
import threading

class EmailThread(threading.Thread):
    def __init__(self, subject, html_content, recipient_list):
        self.subject = subject
        self.recipient_list = recipient_list
        self.html_content = html_content
        self.text_content = strip_tags(html_content)
        threading.Thread.__init__(self)

    def run(self):
        print(f"Starting email thread: {self.subject} -> {self.recipient_list}")
        try:
            val = send_mail(
                self.subject,
                self.text_content,
                settings.DEFAULT_FROM_EMAIL,
                self.recipient_list,
                html_message=self.html_content,
                fail_silently=False,
            )
            print(f"Email sent successfully to {self.recipient_list}. Status: {val}")
        except Exception as e:
            print(f"Failed to send email to {self.recipient_list}: {e}")
            import traceback
            traceback.print_exc()

def send_html_mail(subject, template_name, context, recipient_list):
    html_content = render_to_string(template_name, context)
    EmailThread(subject, html_content, recipient_list).start()

def send_verification_email(user, code):
    subject = "Verify your FaceLook account"
    context = {'user': user, 'code': code}
    send_html_mail(subject, 'emails/verify_account.html', context, [user.email])

def send_password_reset_email(user, code):
    subject = "Reset your FaceLook password"
    context = {'user': user, 'code': code}
    send_html_mail(subject, 'emails/reset_password.html', context, [user.email])

def send_account_update_email(user, changes):
    subject = "Your FaceLook account has been updated"
    context = {'user': user, 'changes': ", ".join(changes)}
    send_html_mail(subject, 'emails/account_update_notice.html', context, [user.email])

def send_password_change_notice_email(user):
    subject = "Security Alert: Your password was changed"
    context = {'user': user}
    send_html_mail(subject, 'emails/password_change_notice.html', context, [user.email])

def send_email_change_verification(user, code, new_email):
    subject = "Verify your new email address"
    context = {
        'user': user,
        'code': code,
        'pending_email': new_email
    }
    send_html_mail(subject, 'emails/email_change_verification.html', context, [new_email])

def send_email_changed_notifications(user, old_email, new_email):
    subject = "FaceLook Account: Email Address Updated"
    context = {
        'user': user,
        'new_email': new_email
    }
    # Notify old address
    send_html_mail(subject, 'emails/email_changed_notice.html', context, [old_email])
    # Notify new address
    send_html_mail(subject, 'emails/email_changed_notice.html', context, [new_email])
