from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site

User = get_user_model()


class CustomAccountAdapter(DefaultAccountAdapter):
    def is_open_for_signup(self, request):
        """
        Whether to allow sign ups.
        """
        return True

    def get_email_confirmation_url(self, request, emailconfirmation):
        """
        Constructs the email confirmation (activation) url.
        """
        get_current_site(request)
        return f"{settings.LOGIN_REDIRECT_URL}verify-email?key={emailconfirmation.key}"

    def send_confirmation_mail(self, request, emailconfirmation, signup):
        """
        Sends the confirmation email.
        """
        current_site = get_current_site(request)
        activate_url = self.get_email_confirmation_url(request, emailconfirmation)
        ctx = {
            "user": emailconfirmation.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": emailconfirmation.key,
        }
        email_template = "account/email/email_confirmation_signup" if signup else "account/email/email_confirmation"
        self.send_mail(email_template, emailconfirmation.email_address.email, ctx)


class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
    def is_open_for_signup(self, request, sociallogin):
        """
        Whether to allow social account sign ups.
        """
        return True

    def populate_user(self, request, sociallogin, data):
        """
        Hook that can be used to further populate the user instance.
        """
        user = super().populate_user(request, sociallogin, data)
        if sociallogin.account.provider == "discord":
            user.discord_id = sociallogin.account.uid
        return user

    def save_user(self, request, sociallogin, form=None):
        """
        Save the newly signed up social login.
        """
        user = super().save_user(request, sociallogin, form)
        return user
