from django.db.models import Count
from django.shortcuts import render, redirect
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.contrib.auth.decorators import login_required
from django.template.loader import render_to_string

import logging
from sikweb.settings import URL

from members.views.utils import *
from kaehmy.models import Application, CustomRole, PresetRole
from kaehmy.forms import ApplicationForm, CommentForm
from kaehmy.tables import ExportTable
from webapp.utils import send_email
from webapp.models import processHooks


@ensure_csrf_cookie
@require_http_methods(["GET"])
def list_view(request, *args, **kwargs):
    """Kaehmy application list"""

    role_filter = request.GET.get("role", None)
    if role_filter is not None and str(role_filter) != "-1":
        applications = Application.objects.filter(
            custom_roles__id=role_filter
        ) | Application.objects.filter(preset_roles__id=role_filter)
    else:
        applications = Application.objects.all()

    applications = applications.order_by("-timestamp")
    filter_options_preset = PresetRole.objects.annotate(
        form_count=Count("forms")
    ).filter(form_count__gt=0)
    filter_options_preset_list = [
        (r.id, r.name, r.form_count) for r in filter_options_preset
    ]
    filter_options_custom = CustomRole.objects.annotate(
        form_count=Count("forms")
    ).filter(form_count__gt=0)
    filter_options_custom_list = [
        (r.id, r.name, r.form_count) for r in filter_options_custom
    ]

    filter_options = filter_options_preset_list + filter_options_custom_list
    filter_options.sort(key=lambda f: f[1])

    context = {
        "applications": applications,
        "application_count": len(applications),
        "filter_options": filter_options,
    }

    return render(request, "kaehmy/list.html", context)


@ensure_csrf_cookie
@require_http_methods(["POST"])
def comment(request, *args, **kwargs):
    """POST endpoint for commenting"""

    form = CommentForm(request.POST)
    if form.is_valid():
        comment = form.save()
        name = comment.name
        url = f"https://{URL}/kaehmy"

        to_email = comment.parent.email
        subject = "Kaehmyysi tai kommenttiisi on vastattu!"
        message = render_to_string(
            "kaehmy/email_comment.html", {"name": name, "url": url}
        )

        send_email(to=to_email, subject=subject, body=message, html=True)
        logging.debug(f"Sent kaehmy comment email to recipient <{to_email}>")

        return redirect("/kaehmy")
    else:
        context = {"error": form.errors}
        return render(request, "kaehmy/error.html", context)


@require_http_methods(["GET"])
def statistics_view(request, *args, **kwargs):
    """Kaehmys roles listed by applications"""

    applications = Application.objects.all()
    role_list = []

    preset_roles = PresetRole.objects.all()
    custom_roles = CustomRole.objects.all()

    for preset in preset_roles:
        people = [form.name for form in preset.forms.all()]
        role_list.append((preset.name, len(people), ", ".join(people)))
    for custom in custom_roles:
        people = [form.name for form in custom.forms.all()]
        role_list.append((custom.name, len(people), ", ".join(people)))

    context = {
        "applications": applications,
        "application_count": len(applications),
        "role_list": role_list,
    }
    return render(request, "kaehmy/statistics.html", context)


@require_http_methods(["GET"])
def view(request, *args, **kwargs):
    """Render Kaehmy form page."""
    form = ApplicationForm()
    return render(request, "kaehmy/kaehmy.html", {"form": form})


@ensure_csrf_cookie
@require_http_methods(["POST"])
def submit(request, *args, **kwargs):
    """Submit Kaehmy form."""
    form = ApplicationForm(request.POST)
    if form.is_valid():
        application = form.save()
        custom_name = form.cleaned_data.get("custom_role_name")
        custom_is_board = form.cleaned_data.get("custom_role_is_board")
        kaehmybot_allowed = form.cleaned_data.get("kaehmybot") == "1"

        if len(custom_name) > 0:
            custom_role = CustomRole(name=custom_name, is_board=custom_is_board)
            custom_role.save()
            application.custom_roles.add(custom_role)

        url = f"https://{URL}/kaehmy"
        name = form.cleaned_data.get("name", "Anonymous")

        to_email = form.cleaned_data.get("email", "")
        subject = "Arwokas kirjattu kirje mahdolliselle tulewalle kiltahenkilölle"
        message = render_to_string(
            "kaehmy/email_kaehmy.html", {"name": name, "url": url}
        )

        send_email(to=to_email, subject=subject, body=message, html=True)
        logging.debug(f"Sent kaehmy email to recipient <{to_email}>")

        processHooks(message=f"Uusi New kaehmy! {name} -> {url}", eventType="kaehmy")
    else:
        context = {"error": form.errors}
        return render(request, "kaehmy/error.html", context)
    return HttpResponseRedirect("/kaehmy")


@require_http_methods(["GET"])
@login_required(login_url="/admin/login")
def export_view(request, *args, **kwargs):
    def make_table(queryset):
        table = ExportTable(
            queryset,
            request=request,
            exclude=["id"],
            attrs={"class": "table table-bordered table-hover"},
        )

        table.paginate(page=request.GET.get("page", 1), per_page=9999)
        table_html = convert_table_to_html(table, request)
        return table_html

    kaehmys = Application.objects.all()
    non_board = filter(lambda q: not q.has_any_board_role(), kaehmys)
    board = filter(lambda q: q.has_any_board_role(), kaehmys)

    context = {
        "non_board_table": make_table(non_board),
        "board_table": make_table(board),
    }
    return render(request, "kaehmy/export.html", context)
