import logging

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
from django.utils.http import urlencode

from ichec_django_core.views import InviteUserView

logger = logging.getLogger(__name__)


class InviteAccessUserView(InviteUserView):

    def post(self, request, *args, **kwargs):
        return super().post(request, args, kwargs)

    def send_email(self, request, user, email, action_url):

        logger.info("Sending user invite email: %s", email)

        login_url = "oidc/authenticate" if settings.WITH_OIDC else "accounts/login"
        base_url = request.scheme + "://" + request.get_host() + "/" + login_url
        if action_url:
            full_url = base_url + "/?" + urlencode({"next": action_url})
        else:
            full_url = base_url

        username = user.email
        if user.first_name and user.last_name:
            username = f"{user.first_name} {user.last_name}"

        context = {"link": full_url, "user_name": username}

        # Email applicant and facility
        emails_dir = "marinerg_test_access/emails"

        template = emails_dir + "/invite_user"
        text = render_to_string(template + ".txt", context=context)
        html = render_to_string(template + ".html", context=context)

        msg = EmailMultiAlternatives(
            subject="MARINERG-i: Portal Signup Invitation",
            body=text,
            from_email=settings.DEFAULT_EMAIL_SENDER,
            to=[email],
            headers={"List-Unsubscribe": f"<mailto:{settings.DEFAULT_EMAIL_UNSUB}"},
        )

        msg.attach_alternative(html, "text/html")
        msg.send()
