from django.views.generic import TemplateView
from django.contrib import messages
from django.contrib.sites.shortcuts import get_current_site
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from django.views.decorators.http import require_http_methods
from django.urls import reverse
from django.shortcuts import redirect

from oscar.core.utils import redirect_to_referrer
from ocyan.core.fender import config
from ocyan.main.loading import get_ocyan_class, get_ocyan_classes

ContactForm = get_ocyan_class("contact_form.forms", "ContactForm")
# pylint: disable=unbalanced-tuple-unpacking
get_from_email, get_to_email = get_ocyan_classes(
    "contact_form.utils", ["get_from_email", "get_to_email"]
)


@require_http_methods(["POST"])
def post_contact_form(request):
    form = ContactForm(request.POST, request=request)

    if form.is_valid():
        context = {
            "website_url": request.build_absolute_uri(),
            "form_data": form.cleaned_data,
        }

        html_message = render_to_string("contact_form/contact_email.html", context)
        text_message = render_to_string("contact_form/contact_email.txt", context)

        site = get_current_site(request)
        site_name = site.name or config.get("django", "name")

        subject = _("Contact form email from %s") % site_name
        msg = EmailMultiAlternatives(
            subject,
            text_message,
            from_email=get_from_email(request, form),
            to=get_to_email(request, form),
            reply_to=[form.cleaned_data["email_from"]],
        )
        msg.attach_alternative(html_message, "text/html")
        msg.send()

        request.session["contact_form_submitted"] = True
        messages.add_message(request, messages.SUCCESS, _("Message sent"))
        return redirect(reverse("contact_form:contact-form-thank-you"))
    else:
        request.session["contact_form_post_data"] = request.POST
        messages.add_message(
            request,
            messages.ERROR,
            _("An error occured in the contact form: %s") % form.errors.as_text(),
        )
        return redirect_to_referrer(request, "contact_form:contact-form-handler")


class ContactFormThankYou(TemplateView):
    template_name = "contact_form/thank_you.html"

    def get(self, request, *args, **kwargs):
        contact_form_submitted = request.session.pop("contact_form_submitted", False)
        if contact_form_submitted:
            return super().get(request, *args, **kwargs)
        else:
            return redirect(settings.CONTACT_REDIRECT_URL)
