from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import Http404
from django import forms
from django.forms import inlineformset_factory
from django.utils.translation import get_language

from .models import KbCategory, KbEntry


def kb_index(request):
    return render(request, 'kb/kb_index.html', {
        'categories': KbCategory.objects.all(),
    })


def kb_category(request, category):
    category = get_object_or_404(KbCategory, slug=category)
    return render(request, 'kb/kb_category.html', {
        'category': category,
        'items': list(KbEntry.objects.filter(category=category)),
    })


def kb_entry(request, category, entry):
    entry = get_object_or_404(KbEntry, category__slug=category, pk=entry, internal=False)
    return render(request, 'kb/kb_item.html', {
        'item': entry,
    })


@login_required
def kb_feedback(request, category, entry):
    entry = get_object_or_404(KbEntry, category__slug=category, pk=entry, internal=False)
    arg = request.GET.get('vote')
    if arg == 'up':
        entry.vote(request.user, 1)
    elif arg == 'down':
        entry.vote(request.user, -1)
    return redirect(entry.get_absolute_url())

