import hashlib
import random

from django.template.loader import render_to_string

from authentication import views as auth_views


def send_invitation_email(to: str, signup_url: str):
    subject = 'Delta Carbon EPC Tool - Team Invitation'
    message = f"Hi, you've been invited to a team. Please click on the link below to join."
    html_message = render_to_string(
        'emails/body.html',
        {
            'email_title': "Team Invitation",
            'email_message': message,
            'team_signup_url': signup_url,
        },
    )

    icons_to_attach = auth_views.get_email_icons()
    email = auth_views.create_email_with_inline_images(subject, html_message, to, icons_to_attach)
    email.send()


def generate_random_token(extra=None, hash_func=hashlib.sha256):
    if extra is None:
        extra = []
    bits = extra + [str(random.SystemRandom().getrandbits(512))]
    return hash_func("".join(bits).encode("utf-8")).hexdigest()


def generate_signup_code_token(email=None):
    extra = []
    if email:
        extra.append(email)
    return generate_random_token(extra)


def account_delete_mark(deletion):
    deletion.user.is_active = False
    deletion.user.save()


def account_delete_expunge(deletion):
    deletion.user.delete()
