import logging
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import ensure_csrf_cookie
from django.http import HttpResponseRedirect
from django.utils.translation import gettext_lazy as _
from django.template.loader import render_to_string

from sikweb.settings import URL

from ohlhafv.models import OhlhafvChallenge
from ohlhafv.forms import OhlhafvForm
from webapp.utils import send_email
from webapp.models import processHooks


@require_http_methods(["GET"])
def ohlhafv_view(request, *args, **kwargs):
    """Render Ohlhafv form page."""
    form = OhlhafvForm()
    return render(request, "ohlhafv/new.html", {"form": form})


@ensure_csrf_cookie
@require_http_methods(["POST"])
def ohlhafv_submit(request, *args, **kwargs):
    """Submit Ohlhafv form."""
    form = OhlhafvForm(request.POST)
    if form.is_valid():
        form.save()
        challenge = form.instance
        url = f"https://{URL}/ohlhafv/list"

        email_body = render_to_string(
            "ohlhafv/email.html",
            {
                "challenge": challenge,
                "url": url,
            },
        )

        to_email = form.cleaned_data.get("victim_email", "")
        subject = "Sinut on haastettu Øhlhäfviin!"
        send_email(to=to_email, subject=subject, body=email_body)
        logging.debug(f"Sent ohlhafv email to recipient <{to_email}>")

        try:
            webhook_message = render_to_string(
                "ohlhafv/tgmsg.tpl", {"challenge": challenge, "url": url}
            )
            processHooks(message=webhook_message, eventType="ohlhafv")
        except Exception:
            pass

    else:
        pass
    return HttpResponseRedirect("/ohlhafv/list/")


@ensure_csrf_cookie
@require_http_methods(["GET"])
def ohlhafv_list(request, *args, **kwargs):
    """Present Ohlhafv challenges list."""
    challenges = OhlhafvChallenge.objects.all()
    challenges = challenges.order_by("-id")
    context = {
        "challenges": challenges,
        "challenge_count": len(challenges),
    }
    return render(request, "ohlhafv/list.html", context)
