"""Ohlhafv views."""

from django.db.models import Count
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import ensure_csrf_cookie
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import permission_required, login_required
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string

import logging
import requests
from dealer.git import git
from sikweb.settings import URL

from ohlhafv.models import OhlhafvChallenge
from ohlhafv.forms import OhlhafvForm
from ohlhafv.tables import OhlhafvTable
from webapp.utils import send_email
from kaehmy.tgbot import TelegramBot


@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
        email = form.cleaned_data.get('victim_email', '')

        url = f'https://{URL}/ohlhafv/list'
        subject = _('Sinut on haastettu Øhlhäfviin!')

        message = render_to_string(
            'ohlhafv:email.html', {
                'challenge': challenge,
                'url': url,
            }
        )
        send_email(email, subject, message)

        try:
            tg_message = render_to_string(
                'ohlhafv:tgmsg.tpl', {
                    'challenge': challenge,
                    'url': url})
            bot = TelegramBot()
            bot.broadcast(tg_message)
        except Exception:     # tg spam is not critical. Ignore on failure
            pass

        logging.debug(
            'Sent ohlhafv email to recipient <{}>'.format(email))
    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)
