from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse

from .models import Article

def index(request):
    latest_article_list = Article.objects.filter(published=True).order_by('-updated')[:5]
    for article in latest_article_list:
        article = article_decoration(article)
    context = {
        'parent_title': 'Knowledgebase',
        'parent_url': reverse('knowledgebase:index'),
        'parent_icon': 'newspaper outline',
        'title': 'Index',
        'icon': 'list',
        'description': 'Index of knowledgebase articles.',
        'keywords': 'knowledgebase, articles, index',
        'latest_article_list': latest_article_list,
    }
    #output = ', '.join([article.title for article in latest_article_list])
    return render(request, 'knowledgebase/index.html', context)

def article(request, article_slug):
    article = get_object_or_404(Article, slug=article_slug)
    article = article_decoration(article)
    context = {
        'parent_title': 'Knowledgebase',
        'parent_url': reverse('knowledgebase:index'),
        'parent_icon': 'newspaper outline',
        'title': article.title,
        'icon': 'file alternate outline',
        'description': article.description,
        'keywords': article.keywords,
        'article': article,
        'category': article.category,
    }
    return render(request, 'knowledgebase/article.html', context)

def edit_article(request, article_slug):
    article = get_object_or_404(Article, slug=article_slug)
    article = article_decoration(article)
    context = {
        'parent_title': 'Knowledgebase',
        'parent_url': reverse('knowledgebase:index'),
        'parent_icon': 'newspaper outline',
        'title': 'Edit ' + article.title,
        'icon': 'file alternate outline',
        'article': article,
    }
    return render(request, 'knowledgebase/edit_article.html', context)

def save_article(request, article_slug):
    article = get_object_or_404(Article, slug=article_slug)
    article.title = request.POST['title']
    article.description = request.POST['description']
    article.category = request.POST['category']
    article.content = request.POST['content']
    article.save()
    return HttpResponseRedirect(reverse('knowledgebase:article', args=(article.slug,)))

def article_decoration(article):
    if article.category == 'ot':
        article.verbose_category = 'Other'
        article.icon = 'archive'
    else:
        article.verbose_category = 'Unkown'
        article.icon = 'question'
    return article
