from django.shortcuts import render
from django.contrib.auth.decorators import permission_required, login_required
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.conf import settings
from django.utils.translation import ugettext as _
from django.forms.models import model_to_dict

import logging
import html

from members.views.utils import *
from members.tables import PaymentTable
from members.forms import PaymentForm
from members.views import error_view


@ensure_csrf_cookie
@require_http_methods(["GET"])
@login_required(login_url='/admin/login')
@permission_required('members.read_payment', raise_exception=True)
def payment_list(request, *args, **kwargs):
    """Render list of payments."""
    search = request.GET.get('q', None)
    if search:
        payments = Payment.find_payments_by_name(search)
    else:
        payments = Payment.objects.all()

    table = PaymentTable(payments,
                         request=request,
                         exclude=['id'],
                         attrs={'class': 'table table-bordered table-hover'})

    table.paginate(page=request.GET.get('page', 1), per_page=25)
    table_html = convert_table_to_html(table, request)

    context = {
        'table': table_html,
        'payment_count': len(payments),
        'notification': request.GET.get('notification', None)
    }
    return render(request, 'payment_list.html', context)


@ensure_csrf_cookie
@require_http_methods(["GET"])
@login_required(login_url='/admin/login')
@permission_required('members.add_payment', raise_exception=True)
def payment_add(request, *args, **kwargs):
    """Render add payment form."""
    form = PaymentForm()
    return render(request, 'payment_add.html', {'form': form})


@ensure_csrf_cookie
@require_http_methods(["POST"])
@login_required(login_url='/admin/login')
@permission_required('members.add_payment', raise_exception=True)
def payment_submit(request, *args, **kwargs):
    """Submit payment."""
    form = PaymentForm(request.POST)
    if form.is_valid():
        form.save()
        logging.info(
            "Saved new payment to member register with the following info: {}"
            .format(form.cleaned_data))
        notification = "{} {}.".format(
            _("Successfully added payment for member"),
            form.cleaned_data['member'])
        return HttpResponseRedirect(
            '/members/payments?notification={}'
            .format(html.escape(notification)))
    else:
        return error_view(request, form.errors)


@ensure_csrf_cookie
@require_http_methods(["GET"])
@login_required(login_url='/admin/login')
@permission_required('members.change_payment', raise_exception=True)
def payment_edit(request, *args, **kwargs):
    """Edit payment."""
    i = kwargs.pop('index', None)
    if i is None:
        return error_view(request, _('No payment id specified'))
    else:
        payment = Payment.objects.get(id=i)
        form = PaymentForm(instance=payment)
        return render(request,
                      'payment_edit.html',
                      {'payment_id': i, 'form': form})


@ensure_csrf_cookie
@require_http_methods(["GET"])
@login_required(login_url='/admin/login')
@permission_required('members.delete_payment', raise_exception=True)
def payment_delete_confirm(request, *args, **kwargs):
    """Render payment delete confirmation page."""
    i = kwargs.pop('index', None)
    if i is None:
        return error_view(request, _('No payment id specified'))
    else:
        payment = Payment.objects.get(id=i)
        form = PaymentForm(instance=payment)
        return render(request,
                      'payment_delete_confirm.html',
                      {'payment_id': i, 'form': form})


@ensure_csrf_cookie
@require_http_methods(["POST"])
@login_required(login_url='/admin/login')
@permission_required('members.delete_payment', raise_exception=True)
def payment_delete(request, *args, **kwargs):
    """Delete payment."""
    try:
        id = request.POST['id']
    except KeyError:
        return error_view(request, _('No payment id specified'))

    try:
        payment = Payment.objects.get(id=id)
        notification = "{} {}.".format(
            _("Successfully deleted payment"), str(payment))
        payment.delete()
        logging.info(
            "Delete payment '{}' in member register".format(str(payment)))
        return HttpResponseRedirect(
            '/members/payments?notification={}'
            .format(html.escape(notification)))
    except:
        return error_view(request, _('Could not delete payment object'))


@ensure_csrf_cookie
@require_http_methods(["POST"])
@login_required(login_url='/admin/login')
@permission_required('members.change_payment', raise_exception=True)
def payment_update(request, *args, **kwargs):
    """Update payment information."""
    form = PaymentForm(request.POST)
    if form.is_valid():
        id = request.POST['id']
        payment = Payment.objects.get(id=id)
        form = PaymentForm(request.POST, instance=payment)
        form.save()

        logging.info(
            "Updated member in member register with the following info: {}"
            .format(form))
        notification = "{} {}.".format(
            _("Successfully updated payment"), str(payment))
        return HttpResponseRedirect(
            '/members/payments?notification={}'
            .format(html.escape(notification)))
    else:
        return error_view(request, _('Could not update payment object'))
